我试图将代码分解为模块,但是在引用应用程序的其他模块时遇到问题。

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的副本,并且没有我需要的新内容。

这是“功能”获得更多方法的方式...当我执行方法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=

最佳答案

与模块或全局无关...区别在于是否要更改对象变量的指向或变量指向的是:

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}

07-24 18:01