Javascript原型链继承的实例分析

Javascript原型链继承的实例分析
本文的示例分析了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程序设计有所帮助。
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部