Private Slots

Claus Reinke claus.reinke at talk21.com
Wed Jan 16 11:55:33 PST 2013


>> Below is a slight variation of the closure "hack" that allows using
>> private properties through this. The idea is to use the public 'this'
>> as prototype for the private 'this', using 'bind' to give instance
>> methods access to the private 'this'
> Bound methods. Smart!
> I come to wonder why you even need the Object.create at all.

I need both a private 'this' (for the methods to use) and a public 
'this' (for the constructor to return, and for the public/clients to 
use), and I need them to be related.

Using Object.create allows to put the private fields before the
public fields in the prototype chain (the public 'this' is the prototype
of the private 'this'), so instance methods can access both while
the public can only access the public 'this'.

Claus
 
>> var MyClass = (function () {
>>
>>    function MyClass(id) {
>>       this.id = id;
>>
>>       var private_this = Object.create(this);  // this and more
>>       private_this.secret = Math.random().toString();
>>
>>       this.guess = guess.bind(private_this);
>>    }
>>
>>    function guess(guess) {
>>      var check = guess===this.secret
>>                ? "I'm not telling!"
>>                : "That guess is wrong!";
>>      console.log("("+this.id+"'s secret is: "+this.secret+")");
>>      console.log(this.id+' says: '+check);
>>    }
>>
>>    return MyClass;
>> })();
>>
>> var myObj1 = new MyClass("instance1");
>> var myObj2 = new MyClass("instance2");
>>
>> console.log(myObj1,myObj2);
>>
>> var guess = Math.random().toString();
>> console.log("guessing: "+guess);
>> myObj1.guess(guess);
>> myObj2.guess(guess);
>>
> 


More information about the es-discuss mailing list