本文實(shí)例分析了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();
當(dāng)我們對(duì)對(duì)象的prototype屬性進(jìn)行完全重寫時(shí),有時(shí)候會(huì)對(duì)對(duì)象constructor屬性產(chǎn)生一定的負(fù)面影響。
所以,在我們完成相關(guān)的繼承關(guān)系設(shè)定后,對(duì)這些對(duì)象的const屬性進(jìn)行相應(yīng)的重置是一個(gè)非常好的習(xí)慣。如下所示:
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;
}
雖然提高了效率,但是這樣的方法有個(gè)副作用,因?yàn)槭且脗鬟f,而不是值傳遞,所以“父對(duì)象”中的name值受到了影響。
子對(duì)象和父對(duì)象指向的是同一個(gè)對(duì)象。所以一旦子對(duì)象對(duì)其原型進(jìn)行修改,父對(duì)象也會(huì)隨即被改變。
再再改寫(使用臨時(shí)構(gòu)造器):
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;
}
雖然提高了效率,但是這樣的方法有個(gè)副作用,因?yàn)槭且脗鬟f,而不是值傳遞,所以“父對(duì)象”中的name值受到了影響。
子對(duì)象和父對(duì)象指向的是同一個(gè)對(duì)象。所以一旦子對(duì)象對(duì)齊原型進(jìn)行修改,父對(duì)象也會(huì)隨即被改變。
希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。