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. 区别
- 实力生成顺序不一致: ES5 的继承先生成了子类实例,再调用父类的构造函数修饰子类实例,ES6 的继承先生成父类实例,再调用子类的构造函数修饰父类实例。
- 效果不一样(构造函数的继承、静态函数和方法的继承)
- es6必须构造函数中要调用super方法,才能生成自己的this对象。