首页 > 解决方案 > 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.

标签: javascriptclassinheritanceecmascript-6

解决方案


该答案解决了最初提出的问题,并且足以帮助 OP 改进问题并立即获得支持。如果您不是仅仅因为球门柱移动了而否决了它,我将不胜感激。

假设你没有疯,这是一个学习练习,学习如何实现它的最好方法是获取 Typescript,使用 extends 编写一个类,以 ES5 为目标对其进行编译,然后查看生成的 JavaScript。确保您的基类具有方法、属性、静态方法、静态属性以及带有混合必需参数和可选参数的构造函数。然后从中派生另一个类并覆盖一些方法并替换一些方法。你会看到认真对待它的人是如何做到的。


推荐阅读