3

假设我有这个模块,并且我希望它自行初始化并附加到它的范围。像这样:现在用jQuery确定'Revealing Module Pattern'模块的范围

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

有没有办法破解这个?

回答

3

我不认为你可以将范围注入到用$ .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像这样的模块模式,可以考虑使用一个更全面的库加载器如或Frame.js

+0

顺便说一句,require.js非常适合这个。谢谢。 – Kriem 2013-11-14 08:28:58

0

JavaScript中的作用域与函数而非对象密切相关。 JS {}中的对象不会创建它自己的范围。我不熟悉的jQuery“揭示模块模式”,但要获得一个独特的范围,你会做这样的事情:

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

})(); 

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

+1

在这个问题上没有改变。 'self'是预定义的并且引用'window'对象。因此,因为他加载并执行另一个.js文件,'self'引用'window'。 – jAndy 2012-04-17 15:14:12

+0

@jAndy我想我没有正确理解他的问题,然后 – Matt 2012-04-17 15:18:12