I am learning javascript and the module pattern, but I made a mistake in my code and it proved wrong some of the concepts I though were true about this pattern. My basic code is like this:
(function(window,$){
//global menu object
var menu = (function(){
//menu tab component
var tab = (function(){
//public properties
var tab = {
init:doStuff
}
//private properties
function doStuff(){
alert("initialising Tab")
}
//return public properties
return tab;
})();
//menu curtain component
var curtain = (function(){
//public properties
var curtain = {
init:doStuff
}
//private properties
function doStuff(){
alert("initialising Curtain")
}
//return public properties
return curtain;
})();
//menu content component
var content = (function(){
//public properties
var content = {
init:doStuff
}
//private properties
function doStuff(){
alert("initialising Content")
}
//return public properties
return content;
})();
//public properties
var menu = {
init:initialiseMenu
}
//private properties
function initialiseMenu(){
//initialise each component of the menu system
tab.init();
curtain.init();
content.init();
}
//final menu object
return menu;
})();
window.menu = menu;
})(window,jQuery);
Then When my page loads and the code is called:
menu.init();
It gives the alerts in order:
initialising tab
initialising curtain
initialising content
As I expect. But if I change the content component to be like this:
//menu content component
var content = (function(){
//public properties
var content = {
init:doStuff
}
//private properties
function doStuff(){
alert("initialising Content")
}
//CHECK ACCESS TO PREVIOUS VARIABLES
curtain.init();
//return public properties
return content;
})();
it gives out the alerts in order:
initialising curtain
initialising tab
initialising curtain
initialising content
So I see that it is able to access the curtain variable even though it wasn't passed into the module as an argument. I thought that each module would be self contained but I have discovered that this is not the case, Is there anyway to make a module only have access to variables you want it too? in particular to my example would be helpful, Thanks Dan.