本文實例分析了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屬性進行對應的重置是一個非常好的習慣。如下圖所示:
TwoD.prototype.constructor = TwofDShape;
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程式設計有所幫助。