Look Ma, no "this" (was: ECMAScript Harmony)

Kris Zyp kris at sitepen.com
Sun Aug 24 21:44:48 PDT 2008


> On Sun, Aug 24, 2008 at 5:10 PM, Kris Zyp <kris at sitepen.com> wrote:
>> [...] I believe it is still possible to emulate private instance
>> variables with prototypes (although much more awkward than with a 
>> "private"
>> attribute). I could demonstrate if desired.
>
> I desire. Please do. Thanks.


Does this count? It is ugly and grossly inefficient (even disables GC) 
without optimization, but I think it provides private instance variables 
with existing semantics (still not sure why that is really that important):

(function(){
    // <boilerplate>
    var privates = [];
    var instances = [];
    function getPrivate(self){
        // look for the private object
        for(var i = 0; i < instances.length; i++){
            if(instances[i] === self){
                // found it
                return privates[i];
            }
        }
        // not found, need to create one on first access
        instances.push(self);
        var thisPrivate = {};
        privates.push(thisPrivate);
        return thisPrivate;
    }
    // </boilerplate>
    Point = function(){
        typeCheck(this); // implicit type check
        getPrivate(this).x = Math.random();
    };
    Point.prototype = {
        getX : function(){
            typeCheck(this);
            return getPrivate(this).x;
        },
        ...
    };
})();

Desugared from:
class Point {
    private var x = Math.random();
    function getX(){
        return this.x;
    }
    ...
}

> Others on this list should comment on class-private vs. instance-
> private.

I am surprised this is up for debate, I would also think that we would want 
instance-private by default.
Kris 



More information about the Es-discuss mailing list