Thursday, May 26, 2011

JavaScript Variable/Function Scope - a Mystery: Part2

All this time I've lived with the impression that "public" methods (declared in a prototype) cannot access "private" members of constructor functions. Turns out that this is possible, as long as the "private" member is declared without var standing in front.

Clazz = function(num) {
var priv = num;
this.pub = priv;
that = this;
}
Clazz.prototype.outsider = function() {
return priv;
}
c = new Clazz(6);
c.priv; // not defined
c.pub; // 6
c.outsider(); // not defined
view raw gistfile1.js hosted with ❤ by GitHub

Compare it with this one:

Clazz = function(num) {
priv = num; // removed the var from the definition
this.pub = priv;
that = this;
}
Clazz.prototype.outsider = function() {
return priv;
}
c = new Clazz(6);
c.priv; // not defined
c.pub; // 6
c.outsider(); // 6!!!
view raw gistfile2.js hosted with ❤ by GitHub

No comments: