Javascript 使用require.js声明本地函数
我有下一个单身汉:Javascript 使用require.js声明本地函数,javascript,requirejs,scope,global,Javascript,Requirejs,Scope,Global,我有下一个单身汉: ( function () { require ( ['module'], function () { module(); } ); } )(); module.js: function module () { alert('yay'); } define (
(
function ()
{
require
(
['module'],
function ()
{
module();
}
);
}
)();
module.js:
function module ()
{
alert('yay');
}
define (function() {
return function(){
alert('yay');
}
});
但是,当我转到控制台时,我看到该模块是在全局范围中定义的,我不想要的东西,因为我希望所有依赖项都在我的单例范围内
我知道require.js的目的之一是避免全局污染,那么,如何以我想要的方式保护我的依赖项不受全局范围的影响?您没有以正确的方式使用
require.js
您应该使用define
函数来定义模块。
在module.js文件中:
function module ()
{
alert('yay');
}
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);
}
});
,或者我不知道,我正在试图弄清楚require.js是如何工作的,这很让人困惑,但你的答案是正确的,我会在几分钟内接受你的,谢谢!)