Open lingxiao-Zhu opened 3 years ago
先将要用到的 Parent、Child 类写在前面。
function Parent(name) { this.hobbies = ['唱', '跳', 'rap']; this.name = name; } Parent.prototype.sayName = function () { console.log(this.name); }; function Child(age) { this.age = age; }
Child.prototype = new Parent('Larry'); const child = new Child(27);
// 改写 Child 类 function Child(name, age) { Parent.call(this, name); this.age = age; } const child = new Child('Larry', 27);
// 改写 Child 类 function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child;
融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。
通过这个方法可以解决组合继承的问题。
创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。
function createObj(o) { const clone = Object.create(o); clone.sayName = function () { console.log('hi'); }; return clone; } Child.prototype = createObj(new Parent('Larry')); const child = new Child(27);
function Child(name, age) { Parent.call(this, name); this.age = age; } const prototype = createObj(Parent.prototype); prototype.constructor = Child; Child.prototype = prototype;
原型链继承
缺点
借助构造函数继承
优点
缺点
组合继承
优点
融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。
缺点
寄生组合继承
通过这个方法可以解决组合继承的问题。
先介绍下寄生继承
寄生组合