es5和es6继承的区别

1. es5的继承

无论如何继承,大致分为参数为对象和函数的继承。本质上就下面三种继承。

1. 原型

Sun.prototype = new Father();

2. 构造

function Son(){
	Father.call(this)
}

3. 组合寄生继承

有三个方案,分别是es6和es5,运算的速度:Object.create > setPrototypeOf > new(proto)

// 寄生组合式继承
let animation = function () {};
let cat = function () {};

Object.setPrototypeOf(cat.prototype, animation.prototype); // es6, 方案一
// cat.prototype = Object.create(animation.prototype); //  方案二
// cat.prototype = Object.create(animation); //  方案二,不加prototype也可以
// cat.prototype.constructor = cat; //  方案二
// cat.prototype = new animation();//  方案三
// cat.prototype.constructor = cat;//  方案三

2. es6的继承

const inherit = (superConstructor, properties) => {
  let { constructor } = properties;

  let SubConstructor = function (...args) {
    superConstructor.call(this, ...args);
    constructor.call(this, ...args);
  };

  SubConstructor.prototype = {
    ...properties,
    constructor: SubConstructor,
  };

  Object.setPrototypeOf(SubConstructor.prototype, superConstructor);

  return SubConstructor;
};```

3. 区别

  1. 实力生成顺序不一致: ES5 的继承先生成了子类实例,再调用父类的构造函数修饰子类实例,ES6 的继承先生成父类实例,再调用子类的构造函数修饰父类实例。
  2. 效果不一样(构造函数的继承、静态函数和方法的继承)
  3. es6必须构造函数中要调用super方法,才能生成自己的this对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值