Why are object initializer methods not usable as constructors?

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Jul 27 08:24:46 UTC 2016


IIRC methods shorthand are the only where `super` is allowed, at least in
Chrome and Firefox.

Accordingly, if you use them as classes, the super won't point at the one
you'd expect, it would point to the object hosting those classes as
properties.

```js
class Animal { setName(name) { this.name = name; } }
class Cat extends Animal { constructor() { super(); super.setName('cat'); }}
let classes = {
  __proto__: {setName: 'nope'}
  Cat
};

new classes.Cat(); // ?
```

I guess you cannot have the best from both worlds.



On Wed, Jul 27, 2016 at 3:49 AM, /#!/JoePea <joe at trusktr.io> wrote:

> I feel like recent changes in the language (ES6+) introduce new features
> that don't have the flexibility as the pre ES6 language that we're used to.
>
> For example, [`super` is static and inflexible](
> https://esdiscuss.org/topic/the-super-keyword-doesnt-work-as-it-should)
> which is not inline with how `this` works.
>
> Object initializer methods are also limited. Suppose I want to define an
> object that contains various constructors. I would be inclined to use
> object-initializer shortcuts:
>
> ```js
> let classes = {
>   Cat() {},
>   Dog() {},
>   Bird() {}
> }
> ```
>
> but this doesn't work:
>
> ```js
> new classes.Dog() // Uncaught TypeError: classes.Dog is not a constructor
> ```
>
> So, here's another failure of intuition (`super` being static was also not
> intuitive). We can fix this by writing:
>
> ```js
> function Cat() {}
> function Dog() {}
> function Bird() {}
>
> let classes = {
>   Cat,
>   Dog,
>   Bird
> }
> ```
>
> but that's not as convenient. What's the reason why we shouldn't be able
> to do that? I feel like JavaScript is being restricted in undesirable ways.
> I love JavaScript because it has always been so flexible, and I would
> expect the new features to continue being flexible. That's what makes
> JavaScript great.
>
> */#!/*JoePea
>
> _______________________________________________
> 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/20160727/c6859f13/attachment.html>


More information about the es-discuss mailing list