我正在尝试将代码分解为模块,但在引用应用程序的其他模块时遇到问题。
MYAPP = (function(my_app)
{
var funcs = my_app.funcs;
var module2 =
{
stupid_function = function ()
{
var some_var = "auwesome!";
//let's call something from the other module...
funcs.do_whatever();
};
};
my_app.module2 = module2;
return my_app;
})(MYAPP);
当 MYAPP.funcs 发生变化时,问题就出现了。例如,当我初始化它并添加新方法时...由于“funcs”是在闭包内部创建的,因此它有 MYAPP.funcs 的副本,并且没有我需要的新内容。
这就是“funcs”获取更多方法的方式...当我执行方法 MYAPP.funcs.init() 时,MYAPP.funcs 会自行重写。
var MYAPP = (function (my_app, $)
{
'use_strict';
my_app.funcs = {};
my_app.funcs.init = function ()
{
panel = my_app.dom.panel;
funcs = my_app.funcs;
query_fns = funcs.query;
my_app.funcs =
{
some_method: function () { ... },
do_whatever: function () { ... }
};
};
return my_app;
}(APP, jQuery));
提前致谢!!
<小时/>如果有人感兴趣......
最佳答案
与模块或全局无关...区别在于您是否要更改对象变量指向或变量指向什么:
var first = {my:"test"};
var second = first; // second points to object {my:"test"}
first.foo = 42; // updating the object, second points to it and can see the change
first = {my:"other"}; // new object, second still points to old {my:"test", foo:42}
关于javascript - 针对 globar var 的私有(private) var 当全局改变时不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784833/