本文實例分析了javascript原型鏈繼承的用法。分享給大家供大家參考。具體分析如下:
代碼如下:function Shape(){
this.name = 'shape';
this.toString = function(){
return this.name;
}
}
function TwoDShape(){
this.name = '2D shape';
}
function Triangle(side,height){
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){
return this.side*this.height/2;
};
}
/* inheritance */
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();
當我們對對象的prototype屬性進行完全重寫時,有時候會對對象constructor屬性產生一定的負面影響。
所以,在我們完成相關的繼承關系設定後,對這些對象的const屬性進行相應的重置是一個非常好的習慣。如下所示:
代碼如下:TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;
改寫:
代碼如下:function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
function TwoDShape(){}
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = '2d shape';
function Triangle(side,height){
this.side = side;
this.height = height;
}
Triangle.prototype = new TwoDShape;
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
return this.side*this.height/2;
}
再改寫(引用傳遞而不是值傳遞):
代碼如下:function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
function TwoDShape(){}
TwoDShape.prototype = Shape.prototype;
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = '2d shape';
function Triangle(side,height){
this.side = side;
this.height = height;
}
Triangle.prototype = TwoDShape.prototype;
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
return this.side*this.height/2;
}
雖然提高了效率,但是這樣的方法有個副作用,因為是引用傳遞,而不是值傳遞,所以“父對象”中的name值受到了影響。
子對象和父對象指向的是同一個對象。所以一旦子對象對其原型進行修改,父對象也會隨即被改變。
再再改寫(使用臨時構造器):
代碼如下:function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
function TwoDShape(){}
var F = function(){}
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = '2d shape';
function Triangle(side,height){
this.side = side;
this.height = height;
}
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
return this.side*this.height/2;
}
雖然提高了效率,但是這樣的方法有個副作用,因為是引用傳遞,而不是值傳遞,所以“父對象”中的name值受到了影響。
子對象和父對象指向的是同一個對象。所以一旦子對象對齊原型進行修改,父對象也會隨即被改變。
希望本文所述對大家的javascript程序設計有所幫助。