ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

手写es5和es6实现原型继承

2021-11-15 17:33:44  阅读:113  来源: 互联网

标签:es6 es5 val Parent 继承 value child 手写 prototype


组合继承(为什么叫组合继承,组合继承就是构造函数继承和原型链继承的组合)

// 组合继承(只需要注意两点)
// 第一点:继承father的属性值。在Children构造函数中调用Father.call(this,val) (构造函数继承)
// 第二点:继承father的方法。let aa = new Father()之后可以aa.getVal(),让Children.prototype = aa,这样Children的实例就可以用到Father的方法了(把子类的prototype设置为父类的实例,也叫做原型链继承)
function Father(val){
    this.val = val
    this.father = 1111
}
function Children(val){
    Father.call(this,val) //构造函数继承:解决原型链继承的缺点:解决了原型链继承造成的引用类型被所有实例共享的问题,但是缺点是function也是引用类型,这样的话就造程了每个子实例都会有相同的方法,造成了内存浪费
}
Children.prototype = new Father() //原型链继承
Father.prototype.getVal = function(payload = ''){
    console.log(this.val + payload)
}
let child = new Children("组合继承")
console.log(child)

运行出来的结果如下

 所以组合继承的缺点也是很明显,就是在继承父类函数的时候调用了父类构造函数,导致子类的原型上多了不需要的父类属性,造成了内存上的浪费

寄生组合继承

function Parent(value) {
  this.val = value
}
Parent.prototype.getValue = function() {
  console.log(this.val)
}

function Child(value) {
  Parent.call(this, value)
}
Child.prototype = Parent.prototype
Parent.prototype.constructor = Child
const child = new Child(1)

child.getValue() // 1
child instanceof Parent // true

es6 class继承

class Parent {
  constructor(value) {
    this.val = value
  }
  getValue() {
    console.log(this.val)
  }
}
class Child extends Parent {
  constructor(value) {
    super(value)
    this.val = value
  }
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true

class 实现继承的核心在于使用 extends 表明继承自哪个父类,并且在子类构造函数中必须调用 super,因为这段代码可以看成 Parent.call(this, value)

当然了,之前也说了在 JS 中并不存在类,class 的本质就是函数。

标签:es6,es5,val,Parent,继承,value,child,手写,prototype
来源: https://www.cnblogs.com/gengzhen/p/15539191.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有