【问题标题】:javascript - Object.create more than one prototypejavascript - Object.create 多个原型
【发布时间】:2016-07-10 09:43:06
【问题描述】:

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

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

还有这个:

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

有什么建议吗?

编辑:我在 CHROME 中使用 THREE.JS

【问题讨论】:

  • Arun P Johny 所链接的是多级继承。您不能像在 C++ 中那样按照您在 JavaScript 中描述的方式进行多重继承。您能否提供更多关于您为什么想要多重继承的信息,也许我们可以提供一个无需多重继承即可实现相同结果的 OM。
  • @ArunPJohny Worth 在我想说的答案中发布它。留下一个没有任何评论/解释的小提琴对于最终在这里的人来说并不是那么有用。
  • 这不是一个three.js的问题。

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


【解决方案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');
};

【讨论】:

  • 看起来很有希望,但我使用 THREE.JS 和 chrome,所以我没有 $Object.assignjQuery...
  • Object.assign 就像 Object.create,它是浏览器的东西
  • mybad,更新的答案,通常是Object.assign({a:1}, {b:2}) 返回{a: 1, b: 2}
  • Object.assign 是 JavaScript 的东西,而不是浏览器的东西。由于它相对较新且尚未在所有浏览器中实现,您可能需要使用 polyfill:npmjs.com/package/object-assign
  • 感谢@nils 的帮助,我只是说浏览器支持它,不需要库
猜你喜欢
  • 1970-01-01
  • 2012-06-29
  • 2013-02-09
  • 1970-01-01
  • 2021-06-08
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多