JavaScript 有哪些继承方式?各有什么优缺点?

1. 原型链继承

function Parent() { this.colors = ['red'] }
Parent.prototype.sayHi = function () {}

function Child() {}
Child.prototype = new Parent()

2. 构造函数继承(call/apply)

function Parent(name) { this.name = name; this.colors = ['red'] }
function Child(name) { Parent.call(this, name) }

3. 组合继承(最常用)

function Parent(name) { this.name = name; this.colors = ['red'] }
Parent.prototype.sayHi = function () {}

function Child(name, age) {
  Parent.call(this, name)   // 第二次调用 Parent
  this.age = age
}
Child.prototype = new Parent()  // 第一次调用 Parent
Child.prototype.constructor = Child

4. 寄生组合继承(最优方案)

function inherit(Child, Parent) {
  Child.prototype = Object.create(Parent.prototype)
  Child.prototype.constructor = Child
}

function Parent(name) { this.name = name }
Parent.prototype.sayHi = function () {}

function Child(name, age) {
  Parent.call(this, name)
  this.age = age
}
inherit(Child, Parent)

5. ES6 class 继承

class Parent {
  constructor(name) { this.name = name }
  sayHi() { console.log(this.name) }
}

class Child extends Parent {
  constructor(name, age) {
    super(name)
    this.age = age
  }
}

同分类其他题目