Accesssing ES6 class constructor function

Boris Zbarsky bzbarsky at mit.edu
Thu Jan 5 21:56:15 UTC 2017


On 1/5/17 2:21 PM, James Treworgy wrote:
> function createInstance(Cotr, args /* array */) {
>     function F() {
>        // this is dynamic in reality but simple example of injecting
> something...
>        this.logger = new Logger();
>
>        var instance = Cotr.apply(this, args)

So the thing is...

This works for script-defined constructors.  But it never worked right 
for constructors of built-ins.

>        return instance; // in case Cotr returns something

At which point you've lost your logger, right?

Specifically, in the ES5 world, if the Cotr that's passed in there is 
Array or Date, say, then instance != this and you don't get the logger 
thing.

The behavior of ES6 constructors is meant to be able to explain the 
construction of such built-ins (and especially the new ones like Map, as 
well as the various DOM built-ins in browsers) _and_ to allow 
subclassing such built-ins usefully.


> So the Cotr can refer to "this.logger" in the constructor. I don't think
> there's a way to do this with dynamic class inheritance since you always
> have to call super() before you can assign any properties in a constructor.

That's unavoidable if you want to allow Cotr to control the actual 
object allocation, which was one of the design constraints here to 
enable built-ins to work the same way as non-built-ins.

-Boris


More information about the es-discuss mailing list