The class operator: a bridge between object and function exemplers

Allen Wirfs-Brock allen at wirfs-brock.com
Mon Nov 14 15:21:30 PST 2011


On Nov 14, 2011, at 2:53 PM, Waldemar Horwat wrote:

> On 11/14/2011 12:16 PM, Allen Wirfs-Brock wrote:
>> /UnaryExpression/ :
>> *class* /UnaryExpression/
>> ...
>> 
>> The semantics are:
>> 1. if /UnaryExpression/ is undefined or null, return the value of /UnaryExpression/.
>> 2. Let /obj/ be ToObject(/UnaryExpression/)
>> 3. Return the result of calling the [[Get]] internal method of /obj/ with argument 'constructor'
>> 
>> Using the class Operator
>> 
>> Prefixing an object exemplar with the class operator turns it into a class exemplar:
>> 
>> let Point = class {
>> x:0,
>> y,0,
>> constructor(x,y} {
>> this.x=x;
>> this.y=y;
>> }
>> };
> 
> I don't understand what you're accomplishing here.  The above appears to be equivalent (modulo the typos) to:
> 
> let Point = function(x, y) {
>  this.x = x;
>  this.y = y;
> };
> 
> The other stuff inside the class is ignored.

I'm gong to add an method to emphasize an implicit point and fix a typo or two (hopefully more than I create). A desugaring of: 

let Point = class {
   x:0,
   y:0,
   offsetBy(aPoint) {
       return new class this(this.x+aPoint.x, this.y+aPoint.y);
  },
  constructor(x,y} {
       this.x=x;
       this.y=y;
   }
};

into ES5(+let) is:

let Point = function(x,y) {
       this.x=x;
       this.y=y;
   };
 Point.prototype.x = 0;
 Point.prototype.y = 0;
 Point.prototype.offsetBy = function(aPoint) {
       return new this.constructor(this.x+aPoint.x, this.y+aPoint.y};
}

without the class operator in the let initializer it would turn into

let Point = {
   x:0,
   y:0,
   offsetBy: function(aPoint) {
       return new this.constructor(this.x+aPoint.x, this.y+aPoint.y},
   constructor: function(x,y} {
       this.x=x;
       this.y=y;
   }
};
Point.constructor.prototype=Point;

all the same pieces, just assembled slightly differently 

Allen


More information about the es-discuss mailing list