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'
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);
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss