class sugar

Peter Michaux petermichaux at gmail.com
Fri Jun 3 21:43:17 PDT 2011


JavaScript has two well-known ways of doing object construction that
could be argued to be class-like. (Trying to be careful with wording
here.) There is the new/prototype/this-based system and there is the
closure-based system.

new/prototype/this-based system -----------------------

function Point(x, y) {
    this.x = x;
    this.y = y;
};

Point.prototype.getDistance = function() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
};


closure-based system ----------------------------------

function makePoint(x, y) {
    return {
        getDistance: function() {
            return Math.sqrt(x * x + y * y);
        }
    };
}


The classes strawman is proposing terse syntax to make the
new/prototype/this-based system more aesthetic.

http://wiki.ecmascript.org/doku.php?id=harmony:classes


Introducing class syntax will be one of the most monumental changes
ever made to ECMAScript and I suggest that unfortunately the proposal
is targeting the wrong version of creating constructors. I've found
the closure-based system more compelling than the
new/prototype/this-based system. My memory even makes me think that
this list was heading in the direction of sugaring the closure-based
system in 2008.

http://www.mail-archive.com/es-discuss@mozilla.org/msg00335.html

Was using class syntax to sugar the closure-based system thrown out as
a possibility for some reason?

Peter


More information about the es-discuss mailing list