Private Slots

David Bruant bruant.d at gmail.com
Tue Jan 15 00:36:27 PST 2013


Le 14/01/2013 19:21, Claus Reinke a écrit :
>
>> From the teachability perspective, I'm tired of explaining the 
>> closure hack to explain "private" properties. Even to some who are 
>> experienced webdevs, I have to explain that they can't access the 
>> "private" property through "this.".
>> The language needs to evolve to the point where people can write 
>> "this[something]" to retrieve private state. Symbols work for that.
>
> 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.

David

>
> 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