Default call constructor behavior

Claude Pache claude.pache at gmail.com
Mon Oct 26 08:35:10 UTC 2015


> Le 26 oct. 2015 à 03:59, Isiah Meadows <isiahmeadows at gmail.com> a écrit :
> 
> According to the current call constructor proposal, the behavior for
> classes without call constructors is to unconditionally throw.
> Shouldn't this be changed to automatically calling the constructor? I
> see this as better for several reasons:
> 
> 1. It's consistent with most of the builtins, including all of the new
> ES6 types.

No, new builtins are specced to protest when you forget `new` (except for `Symbol` where it is the other way round).

> 2. It's easier to integrate into several libraries. I've run into a
> ton of issues with trying to add support for ES6 classes in a specific
> library written for ES5 for this reason. I can use `C.apply(null,
> args)` instead of `new (Function.apply(C.bind,
> [null].concat(args)))()`.

You should use `Reflect.construct()` or a shim for it, here.

Also, note that the expectation that `Foo(...args)` is equivalent to `new Foo(...args)` doesn’t stand for user-defined pre-ES6 constructors unless they include specific boilerplate. So, anyway, you or the library you’re using should not make such an assumption when working with constructors they don’t own. For constructors they own, the call constructor proposal will make easy to opt-in for that feature.

> 3. It's easier to use in functional programming. (`titles.map(Book)`
> instead of `titles.map(title => new Book(title))`)

Fair. But your `Book` constructor should be explicitly documented that it does the same thing when called as when constructed, since that pattern won’t work with all classes. And if the documentation should be explicit, so should be the implementation.

> 4. It's easier to partially apply. It would make the implementation of
> the proposed Function.prototype.partial very easy, as well as simplify
> and speed up Function.prototype.bind for classes, as assumptions can
> be made.

`Function.prototype.partial` might be simplified under the assumption that `Foo(...args)` is equivalent to `new Foo(...args)`, but you can’t make that assumption in the general case, so you have to implement it the "complicated" way anyway. The only potential advantage is that it may be easier for engines to detect when it is possible to do a specific optimisation.

—Claude

> 
> -- 
> Isiah Meadows
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



More information about the es-discuss mailing list