new instantiation design alternatives

Kevin Smith zenparsing at gmail.com
Fri Sep 12 10:50:10 PDT 2014


>
> And it that case, most people we shown the alternatives to prefer this:
> ```js
>  class ColoredPoint extends Point {
>     constructor(x, y, color) {
>         this.color = color;
>     }
> }
> ```
> over
> ```js
>  class ColoredPoint extends Point {
>     constructor(x, y, color) {
>         this = new super(x, y);
>         this.color = color;
>     }
> }
> ```
>

I gotta side with Mark on this one.

Regarding preferring the first over the second, part of that may be because
the syntax for the second is kinda...gnarly.  If we want to merge
allocation with initialization, then I'm going to want to invoke C# (yet
again):

    class ColoredPoint extends Point {
        constructor(x, y, color) : super(x, y) {
           this.color = color;
        }
    }

Here's a sketch of what I'm thinking:

    ClassConstructor:
        constructor ( StrictFormalParameters ) ClassCreateExpression[opt] {
FunctionBody }

    ClassCreateExpression:
        : LeftHandSideExpression

Within the function body of ClassConstructor, "isnew" is a keyword.  It
evaluates to true if the function was called via [Construct] and false
otherwise.

The ClassCreateExpression is only called when the constructor is called via
[Construct].  It is equivalent to returning a value from @@create in the
previous design.  It is required for classes with an extends clause.  If
the result of evaluating the expression is not an object, then an error is
thrown.

Within the ClassCreateExpression:

- "this" refers to the function upon which "new" was evaluated.
- "super" is only allowed as a function call, and is equivalent to "new
BaseClass()", where BaseClass
    is the result of the extends clause.

Simulating two-phase initialization, and making call and construct
equivalent:

    class C {
        constructor(x) : this["@@create"]() {
            if (!isnew)
                return new C();
            this[0] = x;
        }
        static ["@@create"]() {
            var a = [];
            Object.setPrototypeOf(a, this.prototype);
            return a;
        }
    }

An abstract base class:

    class AB {
        constructor() : undefined {}
    }

I think all of the ideas and examples map over pretty well, while avoiding
a TDZ for `this`, "this=", and any funky new tokens.  The cost would be
that you have to use class syntax to get the extended features.  I think
that's a pretty good tradeoff.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140912/114864ab/attachment.html>


More information about the es-discuss mailing list