本文的示例分析了Javascript原型链继承的用法,供大家
参考,具体分析如下:
复制代码代码如下:
函数形状(){
this.name =字;
this.tostring =函数(){
返回this.name;
}
}
函数的TwoDShape(){
this.name =二维形状的;
}
函数三角形(侧面,高度){
this.name = 'triangle;
this.side =侧;
this.height =高度;
this.getarea =函数(){
返回这个边*这个高度2;
};
}
继承
twodshape.prototype =新的形状();
triangle.prototype =新twodshape();
重写对象的原型
属性时,有时会对对象的构造函数属性产生负面
影响。
因此,在完成相关的继承
设置后重置这些对象的const属性是一个好习惯:
复制代码如下:twodshape.prototype.constructor = twodshape;
triangle.prototype.constructor =三角;
重写:
复制代码如下:函数(形状){ }
shape.prototype.name =字;
shape.prototype.tostring =函数(){
返回this.name;
}
功能(twodshape){ }
twodshape.prototype =新的形状();
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name =二维形状的;
函数三角形(侧面,高度){
this.side =侧;
this.height =高度;
}
triangle.prototype =新twodshape;
triangle.prototype.constructor =三角;
triangle.prototype.name = 'triangle;
triangle.prototype.getarea =函数(){
返回这个边*这个高度2;
}
重写(引用
转换而不是值转移):
复制代码如下:函数(形状){ }
shape.prototype.name =字;
shape.prototype.tostring =函数(){
返回this.name;
}
功能(twodshape){ }
twodshape.prototype = shape.prototype;
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name =二维形状的;
函数三角形(侧面,高度){
this.side =侧;
this.height =高度;
}
triangle.prototype = twodshape.prototype;
triangle.prototype.constructor =三角;
triangle.prototype.name = 'triangle;
triangle.prototype.getarea =函数(){
返回这个边*这个高度2;
}
虽然效率有所提高,但这种
方法有副
作用,因为它是引用传递而不是值转移,因此父对象中的name值受到影响。
子对象和父对象指向同一对象。因此,一旦子对象
修改其原型,父对象将立即更改。
重写(使用临时构造函数):
复制代码如下:函数(形状){ }
shape.prototype.name =字;
shape.prototype.tostring =函数(){
返回this.name;
}
功能(twodshape){ }
Var(f =函数){ }
f.prototype = shape.prototype;
twodshape.prototype =新的f();
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name =二维形状的;
函数三角形(侧面,高度){
this.side =侧;
this.height =高度;
}
f.prototype = twodshape.prototype;
triangle.prototype =新的f();
triangle.prototype.constructor =三角;
triangle.prototype.name = 'triangle;
triangle.prototype.getarea =函数(){
返回这个边*这个高度2;
}
虽然效率有所提高,但这种方法有副作用,因为它是引用传递而不是值转移,因此父对象中的name值受到影响。
子对象和父对象指向同一对象。因此,一旦修改了子对象对齐原型,父对象将立即更改。
希望本文能对大家的javascript
程序设计有所帮助。