ES6 class inheritance without "extends" keyword

Nicolas Source

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

Answers

answered 1 week ago Peter Wone #1

This answer addresses the question as originally posed and was good enough to help the OP refine the question and garner immediate upvotes. I'd appreciate it if you didn't downvote it merely because the goalposts have moved.

Assuming that you are not crazy and this is a learning exercise, the best way to learn how to implement this is to get Typescript, write a class using extends, compile it with ES5 as the target, and look at the generated JavaScript. Ensure your base class has methods, properties, static methods, static properties, and a constructor with mixed required and optional parameters. Then derive another class from it and override some methods and replace some. You'll see how it's done by people who got serious about it.

comments powered by Disqus