【发布时间】:2018-11-23 14:19:16
【问题描述】:
我想在没有 extends 关键字的 es6 类中进行继承:
典型方法:
class Foo extends Bar {
contructor() {
...
}
}
我正在寻找的是生成一个具有相同签名但使用此模式的对象:
class Foo {
contructor(Bar) {
// use Bar class somehow
...
}
}
谢谢
== 编辑 ==
上下文:
我为 JS 库 threejs 构建了一个扩展 (ami)。
它提供了在threejs 中无缝工作的新对象。
问题:
threejs 具有为每个对象生成唯一 ID 的内部机制,这对其正确行为至关重要。
当前的实现依赖于 three 作为全局变量公开,因此创建对象的任何人都必须引用它以确保 id 实际上是唯一的。
// in ami
// ID of this object will be unique accros all classes
// that are based of global THREE.Mesh
class Foo extends THREE.Mesh {
contructor() {
...
}
}
使用全局变量可以正常工作,但我想摆脱全局命名空间要求。
如果我没有在 ami 和我的应用程序中引用相同的基本元素,id 可能会发生冲突。
// in ami
import {Mesh} from 'three';
class Foo extends Mesh {
contructor() {
...
}
}
// in my app
import {Foo} from 'ami';
imoport {Mesh} from 'three';
const foo = new Foo(); // it uses "Mesh" from ami as a base.
const mesh = new Mesh(); // it uses current "Mesh" as a base.
// IDs will conflict...
一个可行的解决方案是我在ami 构造函数中提供一个新参数,以提供three 参考:
// in ami
class Foo {
contructor(mesh) {
...
}
}
// in my app
imoport {Mesh} from 'three';
import {Foo} from 'ami';
const foo = new Foo(Mesh);
const mesh = new Mesh();
但是我不知道如何实现这个解决方案。
【问题讨论】:
-
你想这样做吗?当然,您总是可以以 ES5 风格显式地进行继承,但这完全违背了
class语法的目的。 -
到目前为止你尝试过什么?您对
extends的工作原理了解多少,比如需要做哪些事情? -
也许您正在寻找组合而不是继承?只需
this.inner = new Bar。 -
感谢您的反馈,在问题中添加了更多详细信息-
-
Mesh继承自Object3D其中 doesn't do anything weird 关于 uuid。听起来您的代码库很混乱,因此使用import … from 'three'会解析为 three.js 库的两个不同实例。修复你的模块加载器/捆绑器,而不是重写代码。
标签: javascript class inheritance ecmascript-6