我有下一个单身人士:
(
function ()
{
require
(
['module'],
function ()
{
module();
}
);
}
)();
module.js:
function module ()
{
alert('yay');
}
然而,当我回到我的控制台时,我看到这个模块是在全局范围中定义的,是我不想要的,因为我想要我的单例作用域中的所有依赖项。
我理解require.js的目的之一是避免全球污染,那么,如何以我想要的方式保护我的依赖关系不受全局范围的影响呢?
发布于 2014-02-01 12:26:33
您没有正确地使用require.js
。
您应该使用define
函数来定义模块。在文件module.js中:
define (function() {
return function(){
alert('yay');
}
});
模块值是从外部函数返回的值。然后,要要求模块,请使用以下代码:
require(['module'], function (module) {
module();
});
这样,全球就不会受到污染。还可以以这种方式定义需要其他模块的模块:
define (["aModule","anotherModule"],function(aModule,anotherModule) {
return function(){
alert(anotherModule.someThing + aModule.aProperty);
}
});
此外,您还可以在同一个文件中定义多个模块。你只需说出他们的名字:
define("module1",["aModule","anotherModule"],function(aModule,anotherModule) {
return function(){
//a module could be a function, an object or whatever you want
return "this module value is a string";
}
});
define("module2",["module1","anotherModule"],function(module1,anotherModule) {
return function(){
alert(module1 + anotherModule.aProperty);
}
});
https://stackoverflow.com/questions/21503097
复制