Javascript 如何将对象传递给require.js中的模块?
我有这些js文件: main.js:Javascript 如何将对象传递给require.js中的模块?,javascript,requirejs,Javascript,Requirejs,我有这些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: funct
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';
}
};
});
define(['global'],function (global) {
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>
哪里出错了?您只需要将
全局
设置为messages.js函数的参数。requirejs将为您传递它
messages.js:
define(['global'],function () {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
define(['global'],function (global) {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
这样做的副作用是,如果不将模块声明为依赖项,则无法引用该模块。@abc123:感谢您的编辑