JavaScript 继承实现

一、是什么

继承是子类复用父类属性和方法的机制。

二、几种实现方式

1. 原型链继承(不推荐)

Child.prototype = new Parent();

问题:

共享引用类型

2. 构造函数继承

function Parent(name) {
  this.name = name;
}

function Child(name) {
  Parent.call(this, name);
}

3. 组合继承

function Parent(name) {
  this.name = name;
}

Parent.prototype.sayHi = function () {};

function Child(name) {
  Parent.call(this, name);
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

4. ES6 class 继承

class Parent {
  constructor(name) {
    this.name = name;
  }
}

class Child extends Parent {
  constructor(name) {
    super(name);
  }
}

三、总结

继承核心:“复制属性 + 共享方法(原型)”