javascript - Object.create多个原型

时间:2016-03-23 07:49:14

标签: javascript inheritance three.js prototype multiple-inheritance

我希望我的子对象继承多个父对象的原型,这不起作用:

child.prototype = Object.create(parent1.prototype, parent2.prototype);

还有这个:

child.prototype = Object.create(parent1.prototype);
child.prototype.add(Object.create(parent2.prototype));

有什么建议吗?

编辑:我正在使用THREE.JS和CHROME

1 个答案:

答案 0 :(得分:1)

Javascript没有多重继承,唯一的方法就是扩展基类。看看下面的示例,它有点采用MDN Object.create

function SuperClass(){
  //class 1 - has some super staff
  console.log('SuperClass');
}
function OtherSuperClass(){
  //class 2 - has some other super staff
  console.log('OtherSuperClass');
}

//MyClass wants to inherit all supers staffs from both classes
function MyClass() {
  SuperClass.call(this);
  OtherSuperClass.call(this);
}

//inheritance and extension
//extend class using Object.assign
MyClass.prototype = Object.create(SuperClass.prototype); // inheritance
Object.assign(MyClass.prototype, OtherSuperClass.prototype); // extension

//define/override custom method
MyClass.prototype.myMethod = function() {
  console.log('double inheritance method');
};
相关问题