I noted some open issues on "Classes with Trait Composition"

Bob Nystrom rnystrom at google.com
Thu May 19 10:44:19 PDT 2011


On Wed, May 18, 2011 at 6:29 PM, Brendan Eich <brendan at mozilla.com> wrote:

> On May 18, 2011, at 5:57 PM, Bob Nystrom wrote:
>
> class Point {
>   public x = 0, y = 0;
> }
>
> let p = new Point();
> p.x; // 0
>
>
> This is pretty rare, in my experience.
>

I just did some spelunking through some JS code. In about a dozen classes, I
found 88 per-instance properties. Of them, 34 were initialized without
reference to this or a ctor parameter, so about 39% of the properties could
be expressed using the above syntax.

C# and Java both support this and I use it heavily.

 A hard case? If the constructor does set x and y from parameters, then you
> have double-initialization.
>

Well, if you *are* going to initialize it in the ctor, I wouldn't bother
doing so outside of it too. I'm not proposing that an initializer is *required,
*just that it's allowed. This does a few things for me:

1. It lets me make it obvious which instance state is ctor-dependent and
which isn't. This is fairly important to me because I find it makes it
easier to understand a class's state.

2. It's consistent with the rest of the member declarations which allow
initializers:

class Foo {
  public onInstance = 0;
         onPrototype = 0;
  static onCtor = 0;
}

Seems weird to me that the first line would be an error when the other two
aren't.

3. It's consistent with Java and C# which both allow this. Not that we need
to mimic those languages, but it doesn't hurt to make the most of our users'
expectations.

4. It's terse:

class Stack {
  public items;
  constructor() {
    this.items = [];
  }
  ...
}

class Stack {
  public items = [];
  ...
}


- bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110519/a751cc32/attachment-0001.html>


More information about the es-discuss mailing list