using Private name objects for declarative property definition.

Andreas Rossberg rossberg at google.com
Fri Jul 8 14:43:48 PDT 2011


On 8 July 2011 21:16, Allen Wirfs-Brock <allen at wirfs-brock.com> wrote:
> The current versions of the private names proposal
> http://wiki.ecmascript.org/doku.php?id=harmony:private_name_objects  simply
> exposes a constructor for creating unique values can be be used as property
> keys:

Of the several private names proposals around, I find this one
preferable. It is clean and simple, and provides the functionality
needed in an orthogonal manner. It seems worth exploring how well this
works in practice before we settle on something more complicated.

One minor suggestion I'd have is to treat names as a proper new
primitive type, i.e. typeof key == "name", not "object". That way, it
can be defined much more cleanly what a name is, where its use is
legal (as opposed to proper objects), and where it maybe enjoys
special treatment.

> Another alternative that avoids using the 'private' prefix is to allow the
> property name in a property definition to be enclosed with brackets:
> const __x=Name.create();
> const __y=Name.create();
> const __validate=Name.create();
>  Point = {
>      //private members
>      [__x]: 0,
>      [ __y]: 0,
>      [__validate](x,y) { return typeof x == 'number' && typeof y =
> 'number'},
>      //public members
>      new(x,y) {
>           if (!this[__validate](x,y)) throw "invalid";
>           return this <| {
>                   [__x]: x,
>                   [__y]: y
>                  }
>       };
>      add(anotherPoint) {
>            return this.new(this[__x]+another[__x], this[__y]+another[__y])
>      }
> }

I like this notation most, because it can be generalised in a
consistent manner beyond the special case of private names: there is
no reason that the bit in brackets is just an identifier, we could
allow arbitrary expressions. So the notation would be the proper dual
to bracket access notation. From a symmetry and expressiveness
perspective, this is very appealing.

Notation-wise, I think people would get used to using brackets. I see
no good reason to introduce yet another projection syntax, like @.

Whether additional sugar is worthwhile -- e.g. private declarations --
remains to be explored. (To be honest, I haven't quite understood yet
in what sense such sugar would really be more "declarative". Sure, it
is convenient and perhaps more readable. But being declarative is a
semantic property, and cannot be achieved by simple syntax tweaks.)

/Andreas


More information about the es-discuss mailing list