使用require.js声明本地函数

时间:2014-02-01 20:16:33

标签: javascript requirejs scope global

我有下一个单身人士:

(
    function () 
    {
        require
        (
            ['module'], 
            function () 
            {
                module();
            }
        );
    }
)();

module.js:

function module () 
{
    alert('yay');
}

然而,当我进入我的控制台时,我发现该模块是在全局范围内定义的,我不想要的东西,因为我希望我的所有依赖都在我的单例范围内。 / p>

我理解require.js的目的之一是避免全局污染,因此,如何以我想要的方式保护我的依赖关系免受全局范围的影响?

1 个答案:

答案 0 :(得分:1)

您没有以正确的方式使用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);
    }
});