【问题标题】:Determining the scope of a 'Revealing Module Pattern' module with jQuery使用 jQuery 确定“显示模块模式”模块的范围
【发布时间】:2012-04-17 14:57:39
【问题描述】:

假设我有这个模块,我希望它自行初始化并附加到它的作用域。像这样:

(function( scope ) {
    var Module = (function() {
      return {
          init: function(){
              console.log('Initialized');
          }
      };
    })();
    var module = scope.Module = Module;
    module.init();
})( self );

现在的问题是,self 始终是 window。我不想要那个。我希望它成为 jQuery 的$.getScript() 调用和加载它的范围,如下所示:

var Master = (function($) {
    return {
        init: function() { 
            var self = this;
            $.getScript("/js/libs/module.js");
        }
    }
})(jQuery)

有办法破解吗?

【问题讨论】:

    标签: javascript jquery scope module-pattern revealing-module-pattern


    【解决方案1】:

    我认为您不能将作用域注入到使用 $.getScript 调用的自执行脚本中。相反,您必须使用某种导出变量来存储脚本,直到可以注入作用域。

    (function( exports ) {
       exports.Module = function() {
         return {
            init: function(scope){
               console.log('Initialized', scope);
            }
         };
       };
       var module = exports.Module;
    })( exports || window.exports = {} );
    

    然后:

    var self = this; // or whatever you want the scope to be
    $.getScript("/js/libs/module.js", function(){
        exports.Module().init(self);
    });
    

    老实说,如果您将 jQuery 用于这样的模块模式,请考虑使用更全面的库加载器,例如 require.jsFrame.js

    【讨论】:

    • 顺便说一下,require.js 非常适合这个。谢谢。
    【解决方案2】:

    JavaScript 中的作用域与函数密切相关,而不是对象。 JS {} 中的对象不会创建它自己的范围。我不熟悉 jQuery 中的“Revealing Module Pattern”,但是要获得一个独特的范围,你可以这样做:

    (function( scope ) {
        var Module = (function() {
          return new function() {
              this.init = function(){
                  console.log('Initialized');
              }
          };
        })();
    
        var module = scope.Module = Module;
        module.init();
    
    })();
    

    或者,也许更简洁:

    (function( scope ) {
        var Module = new function() {
            this.init = function(){
              console.log('Initialized');
            };
        };
    
        var module = scope.Module = Module;
        module.init();
    
    })();
    

    在这种情况下,范围是模块,而不是窗口。

    【讨论】:

    • 在这个问题上没有任何改变。 self 是预定义的并引用 window 对象。因此,由于他加载并执行了另一个 .js 文件,self 引用了window
    • @jAndy 我想我当时没有正确理解他的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 2023-03-20
    • 2014-05-19
    相关资源
    最近更新 更多