Before ES6 classes, a function could be used as a constructor:
function MyClass(a, b) {
}
Then, the following code is equivalent to a classic instantiation (like let thisObj = new MyClass("A", "B")
):
let thisObj = Object.create(MyClass.prototype)
// Here we know the `this` object before to call the constructor.
// Then, the constructor is called manually:
MyClass.call(thisObj, "A", "B")
… This technique was a way to know the this
object before calling the constructor. But Function.prototype.call()
doesn't work on an ES6 class constructor.
With ES6 we have Reflect.construct()
:
let thisObj = Reflect.construct(MyClass, "A", "B");
But it doesn't provide a way to call the constructor after the this
object is created.
Is it still possible to do that with ES6 classes?
My use case
I would have needed to keep this feature from ES5 to ES6 for a framework. The framework is responsible for instantiating components (which are ES6 classes). A component can create child components (in a tree of components, there is no inheritance here) from its constructor. Then, a child component can query the framework to get its parent from its own constructor. In this case, we have a technical limitation because the framework still doesn't have the return value of the parent component constructor. This is a regression compared to (a transpilation to) ES5.