资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

javascript原型链怎么实现继承

这篇文章主要介绍了javascript原型链怎么实现继承的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇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.prototypenew 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原型链怎么实现继承
分享URL:http://cdkjz.cn/article/psdpec.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220