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
You mixed up two ways of creating modules. The problem is that the private
var tagIdis not the same thing asthis.tagIdLet me start with a version that works and is similiar to what I normally do with AMD modules:
This has one disadvantage: for every object instance the functions are copied in the memory. That’s the only reason to use prototypes. But if you want private variables, you’ll probably waste some RAM anyway.
In your code, if you replace
this.tagIdwith justtagIdyou’ll be using the private variable, but it will be just one, common for all instances.I will think about making your code work and edit if I find a way to do that.
[edit]
What Stephen did is close to what you expected your code to do. I wouldn’t want to exlain how it works and why to a co-worker though.
[edit]
BTW. Take a look at require.js and AMD (module definition)