我正在学习 javascript 和模块模式,但我在代码中犯了一个错误,事实证明,我认为关于这种模式的一些概念是错误的。我的基本代码是这样的:
(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);
然后当我的页面加载并调用代码时:
menu.init();
它按顺序给出警报:
initialising tab
initialising curtain
initialising content
正如我所料。但是,如果我将内容组件更改为这样:
//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;
})();
它按顺序发出警报:
initialising curtain
initialising tab
initialising curtain
initialising content
所以我看到它能够访问窗帘变量,即使它没有作为参数传递到模块中。我认为每个模块都是自包含的,但我发现事实并非如此,是否有办法让一个模块也只能访问你想要的变量?特别是对我的例子会有帮助,谢谢丹。