怎样通过混入(Mixin)实现多继承

js不提供现成的多重继承的方法, 但可以通过Object.assign()来手动实现: 

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

function Father2(age){
    this.age = age;
}

function Son(name, age){
    Father1.call(this,name);
    Father2.call(this,age);
}

Son.prototype = Object.create(Father1.prototype);
Object.assign(Son.prototype, Father2.prototype);

Son.prototype.constructor = Son;
var lilei = new Son("Lilei",23);
lilei.name; // "Lilei"
lilei.age; // 23

 

posted on 2019-10-14 16:49  aisowe  阅读(243)  评论(0编辑  收藏  举报

导航