JavaScript 继承的多种实现

方式一:组合寄生式继承(推荐)

function clone (parent, child) {
  child.prototype = Object.create(parent.prototype);
  child.prototype.constructor = child;
}

function Parent() {
  this.name = 'parent6';
  this.play = [1, 2, 3];
}
Parent.prototype.getName = function () {
  return this.name;
}

function Child () {
  Parent.call(this);
  this.friend = "child5";
}

clone(Parent, Child);

let person = new Child();

方式二:组合继承(原型链 + 借用构造函数)

function Parent3 () {
  this.name = 'parent3';
  this.play = [1, 2, 3];
}

Parent3.prototype.getName = function () {
  return this.name;
}
function Child3() {
  // 第二次调用 Parent3()
  Parent3.call(this);
  this.type = 'child3';
}

// 第一次调用 Parent3();
Child3.prototype = new Parent3();
Child3.prototype.constructor = Child3;

补充

补充:组合继承的代价是「父类构造函数被调用两次」(new + call),最终实例和原型上各挂一份父类属性。寄生组合继承用 Object.create(parent.prototype) 把原型链挂上去,避免重复调用父类,是面试推荐写法。