本文通过混合构造函数于原型方式来实现JS的继承功能。
Polygon为父类,Triangle
Rectangle 为子类。
function Polygon (iSiders){
this.sides = iSiders;
}
Polygon.prototype.getArea = function(){
return 0;
}
function Triangle(iBase,iHeight){
Polygon.call(this,3);
this.base = iBase;
this.height = iHeight;
}
Triangle.prototype = new Polygon();
Triangle.prototype.getArea = function(){
return 0.5*this.base*this.height;
}
function Rectangle(iLength,iWidth){
Polygon.call(this,4);
this.length = iLength;
this.width = iWidth;
}
Rectangle.prototype = new Polygon();
Rectangle.prototype.getArea = function(){
return this.length*this.width;
}
var triangle = new Triangle(12,4);
var rectangle = new Rectangle(22,10);
alert(triangle.getArea);
alert(rectangle.getArea);