我正在尝试使用 requireJS 了解 javascript AMD 模式。我是面向对象编程的新手,也是 requireJS 的新手。我希望有人能在这里帮助我。
我用对象字面量定义了一个名为“module3”的测试模块:
define([], function () {
var _name = 'this is a test3';
var returnedModule3={
name:'test',
getName:getName
}
function getName() {
return _name;
}
return returnedModule3;
});
但是在加载文件后调用此模块时,在 main.js 文件中,我在 firebug 中收到错误消息“TypeError: module3ref is not a constructor”。下面你会看到我的主文件中的代码:
// Load modules and use them
require(['myModule/module3'], function(module3ref){
// do something with the loaded modules
var module3 = new module3ref();
console.log("module3.getName:"+module3.getName());
});
这是否意味着我们不能使用对象字面量来创建模块?
最佳答案
从字面上解释您的问题标题:RequireJS can turn object literals directly into AMD modules ,例如:
define({
getName: function() {
return 'this is a test3';
},
name: 'test'
})
但是,使用这种模式,一个属性不可能引用它的“邻居”(但这是 JS 对象字面量语法的限制,而不是 RequireJS 本身)。
关于javascript - 如何使用对象文字作为 requirejs 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20825318/