Skip to content

Instantly share code, notes, and snippets.

@joliss
Last active October 20, 2015 15:08
Show Gist options
  • Select an option

  • Save joliss/4a3682494f9c1c4c528d to your computer and use it in GitHub Desktop.

Select an option

Save joliss/4a3682494f9c1c4c528d to your computer and use it in GitHub Desktop.

Call constructor should be static and inherited

I'd like to argue that call constructors should behave like static methods and be inherited, because it would be surprising if they didn't.

Here's a use case:

We can currently use static methods to instantiate classes, as an alternative to new:

class Base {
  static create() { return new this(); }
}

class Sub extends Base {
}

console.log(new Sub);      // => Sub instance
console.log(Sub.create()); // => Sub instance (same)

Note that we use this to access the class, and that create is inherited.

Looking at this example, it seems reasonable to extrapolate that Sub() would be a static method call just like Sub.create().

This would mean that we can rewrite the .create method to be a call constructor like so:

// My proposed behavior:

class Base {
  call constructor() { return new this(); }
}

class Sub extends Base {
}

console.log(new Sub);      // => Sub instance
console.log(Sub());        // => Sub instance (same)

The current spec doesn't seem to allow for this. It seems that maybe it should.

P.S. If we do decide to make call constructors static and inherited, then maybe we should consider renaming them to better reflect this - I sketched out some ideas. This is just a nitpick though. I mostly care about getting the semantics right.

@joliss

joliss commented Oct 20, 2015

Copy link
Copy Markdown
Author

Gist doesn't notify me about comments - let's use Twitter to discuss: https://twitter.com/jo_liss/status/656485512576946176

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment