如何在require.js中传递一个对象给一个模块

How to pass an object to an module in require.js?

本文关键字:模块 一个 一个对象 require js      更新时间:2023-09-26

我有这些js文件:

main.js:

requirejs(['app']);

app.js:

define(['messages'], function (messages) {    
    alert(messages.getHello());
});

messages.js:

define(['global'],function () {
    var privateFn = global.getObj()
    return {
        getHello: function () {
            if(privateFn.hello == "test!")
                return 'Hello World';
        }
    };
});    

global.js:

define(function () {
    var stateObj = {hello:"test!"};
    return {
         getObj: function () { return stateObj; }
    };
});

和index.html为:

<!DOCTYPE html>
<html>
    <head>
        <!-- Include the RequireJS library. We supply the "data-main" attribute to let 
             RequireJS know which file it should load. This file (scripts/main.js) can
             be seen as the entry point (main) of the application. -->
        <script data-main="scripts/main" src="lib/require.js"></script>
    </head>
    <body>
        <h1>Example 2: load module using explicit dependency syntax</h1>
    </body>
</html>

然而,当我打开index.html时,我在控制台得到以下错误:

Uncaught ReferenceError: global is not defined  messages.js

我在哪里出错了?

您只需要将global设置为messages.js函数的参数。requirets会帮你传递的。

messages.js:

define(['global'],function (global) {
    var privateFn = global.getObj()
    return {
        getHello: function () {
            if(privateFn.hello == "test!")
                return 'Hello World';
        }
    };
});

这有一个简洁的副作用,如果不将模块声明为依赖,就不可能引用它。