本文给出了一个例子来描述javascript原型链中学习记录的继承。分享给大家参考,如下:
海量开放网络课程中学习继承的注意事项:
几种继承方式:
(1)使用构造函数实现继承
函数Parent(){ this . name=' Parent ';}函数Child(){ parent . call(this);//执行子类函数体中父类的构造函数this.type=' child//子类自己的属性}Parent.call(this),这是一个实例,用这个执行Parent方法,然后用this.name='parent '放属性
它安装在这个(实例)上,从而实现继承。
缺点:上面只允许子节点获取父节点上的属性,但是父节点原型链上的属性没有继承。
利用原型链实现继承
函数Parent(){ this . name=' Parent ';}函数Child(){ this . type=' Child ';} child . prototype=new Parent();解释:_ _ prototype _ _===实例的子实例的原型
因此,当我们提到新的Child()时。名字,Child上没有名字,然后我们找原型Child。_ _ proto _ _,即Child.prototype,即新的Parent()。父实例上有名称属性,所以子实例在原型链上找到名称属性,从而实现继承。
缺点:可以看到所有的子实例都有相同的原型,即父实例:
var a=new Child();var b=新的Child();a. _ _ proto===b. _ _ proto _ _//真。因此,当a.name='a '用于重新分配名称时,b.name就变成了' a ',反之亦然。
实例或构造函数都不能确认实例是子实例还是父实例。
前两者结合,取长补短
函数Parent(){ this . name=' Parent ';}函数Child(){ parent . call(this);this.type=' child} child . prototype=new Parent();缺点:在Child()中使用parent . call(this);执行一次Parent(),然后使用Child执行一次Parent(),prototype=new Parent()。
改进1:
函数Parent(){ this . name=' Parent ';}函数Child(){ parent . call(this);this.type=' child} child . prototype=parent . prototype;缺点:实例或构造函数都不能确认实例是子实例还是父实例。
原因:孩子。prototype=Parent.prototype直接从Parent获取构造函数。原型,即父母。
改进2:
函数Parent(){ this . name=' Parent ';}函数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编程有所帮助。