lingxiao-Zhu / blog

总结积累,读书笔记
3 stars 0 forks source link

Javascript 常见继承方式和优缺点 #28

Open lingxiao-Zhu opened 3 years ago

lingxiao-Zhu commented 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;