当全局变化时,针对globar var的私有变量不会改变

时间:2012-10-08 15:31:08

标签: javascript closures globals

我正在尝试将代码分解为模块,并且在引用应用程序的其他模块时遇到问题。

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));

提前致谢!!


如果对任何人都有意思......

我用于修改的方法是“紧密增强”http://webcache.googleusercontent.com/search?hl=es-419&q=cache%3Aadequatelygood.com%2F2010%2F3%2FJavaScript-Module-Pattern-In-Depth&btnG=

1 个答案:

答案 0 :(得分:0)

与模块或全局无关......不同之处在于,如果要更改对象变量点或指向哪个变量:

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}