Javascript中的多原型继承

Javascript中的多原型继承,javascript,inheritance,prototypal-inheritance,Javascript,Inheritance,Prototypal Inheritance,我有两个基类,比如ParentClass1和ParentClass2。现在我想对ChildClass执行多个原型继承 对于一个单亲类,我的代码如下所示 var ParentClass=function(){ }; ParentClass.prototype.greetUser=函数(名称){ log('Hi.Hello',name); }; var ChildClass=函数(名称){ 这是greetUser(姓名); }; ChildClass.prototype=Object.create

我有两个基类,比如
ParentClass1
ParentClass2
。现在我想对
ChildClass
执行多个原型继承

对于一个单亲类,我的代码如下所示

var ParentClass=function(){
};
ParentClass.prototype.greetUser=函数(名称){
log('Hi.Hello',name);
};
var ChildClass=函数(名称){
这是greetUser(姓名);
};
ChildClass.prototype=Object.create(ParentClass.prototype);
var obj=新的子类(“John”);

//嗨。您好,John
prototype
属性执行两个赋值不是很有用,因为最后一个赋值将覆盖第一个赋值。您可以这样做,因为接受更多参数:

Object.assign(ChildClass.prototype, ParentClass1.prototype, ParentClass2.prototype);
请注意,
Object.assign
执行浅复制。必须创建一个副本:您需要一个与其他两个原型不同的原型对象:两者的联合。因此,不可避免地需要以某种方式将父原型的成员复制到目标原型对象中

一些警告: 1. <代码>对象。分配生成浅拷贝 由于
Object.assign
执行浅拷贝,您可能会遇到干扰父原型的情况。这可能是你想要或不想要的

例如:

var ParentClass1=函数(){
};
ParentClass1.prototype.userList=[];
ParentClass1.prototype.addUser=函数(名称){
this.userList.push(name);
};
var ParentClass2=函数(){
};
ParentClass2.prototype.askUser=函数(名称){
log('嘿,你好吗',名字);
};
var ChildClass=函数(名称){
这是askUser(姓名);
};
赋值(ChildClass.prototype,ParentClass1.prototype,ParentClass2.prototype);
var p=新的父类1(“父类”);
var obj=新的子类(“John”);
对象addUser('Tim');//添加到child,但是

console.log(p.userList);//现在父对象也有了Tim…
对象。分配不做深度克隆。这很肤浅。我在问,这是对原型继承进行多重继承的正确方法吗?或者有更好的方法吗?有不同的方法,这就是其中之一。如果这适合你的需要,那就好了。