javascript - ES6 class inheritance without "extends" keyword
问题描述
I'd like to do inheritance in an es6 class without the extends
keyword:
Typical approach:
class Foo extends Bar {
contructor() {
...
}
}
What I am looking for is to generate an object with the same signature but using this pattern:
class Foo {
contructor(Bar) {
// use Bar class somehow
...
}
}
Thanks
== EDITS ==
Context:
I build an extension (ami
) for a JS library threejs
.
It provides new objects that seamlessly work in threejs
.
Problem:
threejs
has an internal mechanism to generate unique ids for each object, that is critical for its proper behavior.
Current implementations rely on three
to be exposed as a global variable, so anybody that creates an object must reference it to ensure the ids are actually unique.
// 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() {
...
}
}
Using global variable works fine but I want to get rid of the global namespace requirement.
If I do not reference the same base elements in ami
and in my application, id can conflict.
// 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...
One solution that could work is that I provide a new argument in ami
constructors, to provide the three
reference:
// 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();
But I do not know how to implement this solution.
解决方案
该答案解决了最初提出的问题,并且足以帮助 OP 改进问题并立即获得支持。如果您不是仅仅因为球门柱移动了而否决了它,我将不胜感激。
假设你没有疯,这是一个学习练习,学习如何实现它的最好方法是获取 Typescript,使用 extends 编写一个类,以 ES5 为目标对其进行编译,然后查看生成的 JavaScript。确保您的基类具有方法、属性、静态方法、静态属性以及带有混合必需参数和可选参数的构造函数。然后从中派生另一个类并覆盖一些方法并替换一些方法。你会看到认真对待它的人是如何做到的。
推荐阅读
- excel - VBA允许在工作表保护时创建列表框
- python - 如果 x% 变化,则删除列表元素
- tomcat9 - Spring Boot 2 REST 应用程序无法在 Tomcat 9 上运行
- python - 将 OSM 节点转换为纬度/经度
- android - 如何在颤动中播放音频文件?
- r - 如何在数据帧计算中用向量函数替换 R 中的 for 循环?
- linear-programming - 多重最优解问题中的人工变量 - 线性规划
- css - 分辨率无关的 SVG 过滤器
- django - 如何更改 Django 中 DateTime 字段中日期的显示格式?
- swift - 高阶函数生成两个日期之间的日期间隔?