Newbie Javascript question:
how does one access a private class property in a public method? In all the example I see a public prototype function accessing public (this.property). Is it possible to access a private property in a public method?
Newbie Javascript question:
how does one access a private class property in a public method? In all the example I see a public prototype function accessing public (this.property). Is it possible to access a private property in a public method?
This pattern is known as a "privileged" method. It looks something like this:
function MyClass() {
var secret = "foo";
this.tellSecret = function() {
return secret;
};
}
var inst = new MyClass();
console.log(inst.tellSecret()); // => "foo"
console.log(inst.secret); // => undefined
This works because the private variable is in a closure. The problem with this is that we are putting the privileged method on each instance, rather than the prototype. This is not ideal. Often, instead of having private variables in JavaScript, authors will just use a leading underscore which is conventionally used to imply that public methods/properties should be treated as private:
function MyClass() {
this._secret = "foo";
}
MyClass.prototype.tellSecret = function() {
return this._secret;
};
Here is a little demo:
var Foo = function(name){
this.name = name;
var t = name;
if(typeof(this.show) != 'function'){
Foo.prototype.show = function(){
console.log(t);
console.log(this.name);
};
}
};
var a = new Foo('a');
var b = new Foo('b');
b.show(); // ...
Hope it can help you out.