JavaScript Prototype and Encapsulation
- by Adam Davies
Sorry I'm probably being a realy noob here...but:
I have the following javascript object:
jeeni.TextField = (function(){
var tagId;
privateMethod = function(){
console.log("IN: privateMethod");
}
publicMethod = function(){
console.log("IN: publicMethod: " + this.tagId);
}
jeeni.TextField = function(id){
console.log("Constructor");
this.tagId = id;
}
jeeni.TextField.prototype = {
constructor: jeeni.TextField,
foo: publicMethod
};
return jeeni.TextField;
}());
Now when I run the following code I get the corresponding result:
var textField1 = new jeeni.TextField(21); // Outputs: Constructor
textField1.foo(); // Outputs: IN: publicMethod: 21
console.log(textField1.tagId); // Outputs: 21
console.log(textField1.privateMethod); // Outputs: undefined
So my question is why is privateMethod hidden and tagId is not. I want them both to be private scope.
Please help a noob.
Thanks