javascript原型链学习记录之继承实现方式分析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript原型链学习记录之继承实现方式分析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2285字,纯文字阅读大概需要4分钟。
内容图文
本文实例讲述了javascript原型链学习记录之继承实现方式。分享给大家供大家参考,具体如下:
在慕课网学习继承的笔记:
继承的几种方式:
① 使用构造函数实现继承
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); //在子类函数体里面执行父类的构造函数 this.type = 'child';//子类自己的属性 }
Parent.call(this)
,this即实例,使用this执行Parent方法,那么就用this.name = 'parent'
把属性
挂载在了this(实例)上面,以此实现了继承。
缺点:以上只是让Child得到了Parent上的属性,Parent的原型链上的属性并未被继承。
② 使用原型链实现继承
function Parent(){ this.name = 'parent'; } function Child(){ this.type = 'child'; } Child.prototype = new Parent();
解释:Child.prototype === Chlid实例的__proto__ === Child实例的原型
所以当我们引用new Child().name
时,Child上没有,然后寻找Child的原型child.__proto__
即Child.prototype
即new Parent()
,Parent的实例上就有name属性,所以Child实例就在原型链上找到了name属性,以此实现了继承。
缺点:可以看出,Child的所有实例,它们的原型都是同一个,即Parent的实例:
var a = new Child(); var b = new Child(); a.__proto === b.__proto__; //true
所以,当使用 a.name = 'a'重新给name赋值时,b.name也变成了'a',反之亦然。
用instanceof和constructor都无法确认实例到底是Child的还是Parent的。
③ 结合前两种取长补短
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = new Parent();
缺点:在Child()里面用Parent.call(this);
执行了一次Parent(),然后又使用Child.prototype = new Parent()
执行了一次Parent()。
改进1:
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = Parent.prototype;
缺点:用instanceof和constructor都无法确认实例到底是Child的还是Parent的。
原因: Child.prototype = Parent.prototype
直接从Parent.prototype
里面拿到constructor,即Parent。
改进2:
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;
画图说明吧:
var a = new Child();
所以这样写我们就构造出了原型链。
更多关于JavaScript相关内容还可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
内容总结
以上是互联网集市为您收集整理的javascript原型链学习记录之继承实现方式分析全部内容,希望文章能够帮你解决javascript原型链学习记录之继承实现方式分析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。