Can `new` be optional?

J Decker d3ck0r at gmail.com
Sun Nov 5 19:53:50 UTC 2017


On Sun, Nov 5, 2017 at 7:53 AM, Andrea Giammarchi <
andrea.giammarchi at gmail.com> wrote:

> oldie but goldie ?
>
> ```js
> Object.defineProperty(
>   Function.prototype,
>   'new',
>   {
>     configurable: true,
>     value(...args) {
>       return new this(...args);
>     }
>   }
> );
> ```
>
> doesn't make new optional, just moves it, and doesn't apply to 'class'es
which the OP is saying.


>
>
>
>
> On Sun, Nov 5, 2017 at 11:28 AM, Oriol _ <oriol-bugzilla at hotmail.com>
> wrote:
>
>> > Why can't `new` be optional?
>>
>> When you call a function, you are using the internal [[Call]] method.
>> When you use the `new` operator, it's the internal [[Construct]] method.
>>
>> They are different things, so IMO avoiding `new` when you are
>> instantiating is bad practice.
>>
>>
Of course it is... with out new, classes throw an exception.

This seems like a really short sighted issue.  Why can't calling a class
just invoke it's constructor?

I also don't see how decorators can solve it.

Seems just as arbitrary as the underscore proposal not accepting underscore
trailing a number or before or after a decimal.

Maybe, it would be better to ask 'Why does calling a class throw an
exception instead of just creating a new instance.


> But if you really want to avoid `new` when using ES6 `class` syntax, you
>> can use proxies, e.g.
>>
>> ```js
>> let MyClass = new Proxy(class MyClass {
>>   constructor(arg) { this.arg = arg; }
>> }, {
>>   apply: (target, thisArg, args) => Reflect.construct(target, args)
>> });
>> MyClass(1); // { arg: 1 }
>> new MyClass(2); // { arg: 2 }
>> ```
>>
>
At the cost of non-zero overhead.


> --Oriol
>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171105/cf03d02c/attachment.html>


More information about the es-discuss mailing list