why not "new" instead of "constructor"?

Allen Wirfs-Brock allen at wirfs-brock.com
Sat Nov 19 09:34:01 PST 2011


<meta>In the following I'm going to use syntax from by class operator strawman: http://wiki.ecmascript.org/doku.php?id=strawman:class_operator However, the basic idea should be applicable to several of the class declarations proposal that are drifting about.

BTW, I'm  pretty sure that this isn't the first time the idea has been suggested.  We've had lots of class proposals go by with lots of moving parts.  Some of those parts may be useful even if the whole proposals didn't stick.
</meta>

The current thinking is that a class exemplar is defined as

let Point = class {
   x: 0,  //not really needed unless defining an object exemplar 
   y: 0, 
   constructor(x,y) {
      this.x = x;
      this.y=y;
   }
}

and instantiated as
   new Point(1,2);   //call the constructor method from the class exemplar

There is semantics included in the class operator proposal and other class proposals to cover what happens with the constructor isn't explicitly defined.

However, another issue is that "constructor" is an ugly and idiomatic name. 

Why can't we just use "new" in such declarations:

let Point = class {
   x: 0,  //not really needed unless defining an object exemplar 
   y: 0, 
   new(x,y) {
      this.x = x;
      this.y=y;
   }
};
   
It is shorter to type, reads better, and is much more suggestive of its direct relationship with the new operator.

The only real issue I can think of is that in ES5 unquoted "new" is a valid property name in an object literal.  However, in this case we are using it in a new syntactic context (a concise method property) that doesn't exist in ES5.  Whether or not we also let gave new this meaning in a propertyAssignment form (a breaking change) can be a secondary design decision to be considered.  Related would be concern that there are frameworks that actually use obj.new() as an idiom.  We probably would need to be careful to not break those, but I think that is also doable.  

There are various semantic details that need to be specified, but none of them seem difficult.  Before getting into them, I'm more interested in what is essentially a bikesheding questions:  is this a direction that we shoud consider?

allen





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


More information about the es-discuss mailing list