笔记:JS继承方式

1.创建基类

function Polygon(iSides){
  this.sides = iSides;
}
Polygon.prototype.getArea = function(){
  return 0;
};

 

2.创建子类

function Triangle(iBase,iHeight){
  Polygon.call(this,3);
  this.base = iBase;
  this.height = iHeight;
}

Triangle.prototype = new Polygon();
Tirangle.prototype.getArea = function(){ //覆盖父类方法
  return 0.5 * this.base * this.height;
};

 

function Rectangle(iLenght,iWidth){
  Polygon.call(this,4);
  this.length = iLength;
  this.width  = iWidth;
}

Retangle.prototype = new Polygon();
Retangle.prototype.getArea = function(){ //覆盖父类方法
  return this.height * this.width;
};

 

3.测试代码

var triangle = new Triangle(12,4);
var rectangle = new Rectangle(22,10);

alert(triangle.sides); //outputs "3";
alert(triangle.getArea); //outputs "24";

alert(rectangle.sides); //outputs "4";
alert(rectangle.getArea); //outputs "220";
posted @ 2010-08-15 12:48  rock506  阅读(146)  评论(0编辑  收藏  举报