object.assign拷贝prototype实现多继承

1. 单继承

// Shape - 父类(superclass)
function Shape() {
  this.x = 0;
  this.y = 0;
}

// Rectangle - 子类(subclass)
function Rectangle() {
  //借用父类构造函数
  Shape.call(this);
}

// 子类续承父类
Rectangle.prototype = Object.create(Shape.prototype);
// 恢复构造函数
Rectangle.prototype.constructor = Rectangle;

2. 多继承

function MyClass() {
    //所有父类构造函数借用
    SuperClass.call(this);
    OtherSuperClass.call(this);
}

// 使用Object.create继承一个类,此时继承了SuperClass的原型链
MyClass.prototype = Object.create(SuperClass.prototype);

// 使用Object.assign拷贝其他父类的方法到自身的prototype
Object.assign(MyClass.prototype, OtherSuperClass.prototype);

// 恢复constructor
MyClass.prototype.constructor = MyClass;

//若不使用Object.create, 全部使用Object.assign, 对象为使用{},会继承Object的原型链,造成原型链断裂
//MyClass.prototype = Object.assign({},SuperClass.prototype,OtherSuperClass.prototype);
原文地址:https://www.cnblogs.com/mengff/p/12854089.html