Why are object initializer methods not usable as constructors?

Tab Atkins Jr. jackalmage at gmail.com
Thu Jul 28 16:11:13 UTC 2016


On Wed, Jul 27, 2016 at 11:44 AM, /#!/JoePea <joe at trusktr.io> wrote:
> What's the good reason that object-initializer methods can't be constructors
> though? I mean, I get that "that's what spec says", but what's the actual
> good reason?

Because they're methods, not functions. The distinction between the
two was merely semantic in ES5, but now it's mechanical, due to
super(); constructing something intended as a method would make
super() behave in confusing and unintuitive ways, so methods just
don't have a constructor any more.

There are several very similar ways you can write your example that do
achieve what you want. As Allen said, you can just use the non-concise
syntax, explicitly typing "function" (or better, "class") for each of
the values.  This is only a few characters more and achieves exactly
what you want.

It's been explained to you already in previous threads why super() is
designed the way it is, and how a dynamic super() would add
significant cost to some situations.  Making this one niche use-case
("I want to define several constructor-only classes inline in an
object initializer") require a few characters less is not a
sufficiently worthwhile benefit for the cost.  Just type the few extra
characters (exactly what you would have typed in ES5, so it's not even
a new imposition), and you'll be fine.

~TJ


More information about the es-discuss mailing list