I want a main object M containing a sub-object S which has some method E which has a private variable P. I also want the method E to have access to M via another variable V. For the private variables I’m doing this:
M.S = function () {
var P,
V; // how to set V to M?
return {
E: function () {
// stuff goes here
}
}
}();
One solution I came up with was to remove the () at the last line, and then calling the anonymous S-creating function as a method of M. this solves the problem, but I’m thinking there might be a more elegant way to go about it.
M.S = function () {
var P,
V = this;
return {
E: function () {
// stuff goes here
}
}
};
M.S = M.S()
Mostly I need to know what is good practice for this, since I’m new to private variables in Javascript.
A pretty straightforward method to do this is:
Vis locally declared through the formal parameter.M‘s reference is assigned toV, throughfunction(V){...}(M);.Even when
Mis redeclared at a later point,Vwill still point to the right object.