廢話不說,直接說類的最好的繼承方式:
混合方式,即用對象冒充繼承建構函式的屬性,用原型鏈繼承prototype對象的方法:
看了例子就明白:
function ClassA(sColor){
this.color = sColor;
}
ClassA.prototype.sayColor = function (){
alert(this.color);
}
function ClassB(sColor,sName){
ClassA.call(this,sColor); //冒充繼承,call
this.name = sName;
}
ClassB.prototype = new ClassA();//原型鏈繼承
ClassB.prototype.sayName = function (){
alert(this.name);
}
var objA = new ClassA("red");
var objB = new ClassB("blue","kit");
objA.sayColor();//outputs "red"
objB.sayColor();//outputs "blue"
objB.sayName(); //outputs "kit"
更為實際的例子:
基類:多邊形Polygon (屬性:side--邊的個數;方法:getArea()--計算面積)
子類1:三角形Triangle(增加屬性:base--底,height--高 ;重寫方法:getArea()--低×高/2)
子類2:矩形Rectangle(增加屬性:length--長,width--寬;重寫方法:getArea()--長×寬)
UML
//類Polygon:
function Polygon(iSides){
this.side = iSides;
}
Polygon.prototype.getArea = function (){
return 0;
}
//類Triangle:
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;
}
//類:Rectangle
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 objTriangle = new Triangle(5,6);
var objRectangle = new Rectangle(22,10);
alert(objTriangle.side);
alert(objTriangle.getArea());
alert(objRectangle.side);
alert(objRectangle.getArea());