Immediate invocation to the rescue!
var myObj = (function () {
var that = {
theValue: "The rain in Spain",
functionA: function() {
alert(this.theValue); // or that.theValue, both work here
},
moreFunctions: {
functionB: function() {
alert(that.theValue);
}
}
};
return that;
}()); // <-- immediate invocation !!
You can decompose it even further:
var myObj = (function () {
function functionA() {
alert(that.theValue);
}
function functionB() {
alert(that.theValue);
}
var that = {
theValue: "The rain in Spain",
functionA: functionA,
moreFunctions: {
functionB: functionB
}
}
return that;
}());
If you're familiar with OOP, you can use this to make private variables.