如何使用Object literal作为requirejs模块?

时间:2013-12-29 12:49:25

标签: javascript requirejs

我正在尝试使用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不是构造函数”。您将在下面看到我的主文件中的代码:

// 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()); 
});

这是否意味着我们不能使用object literal来创建模块?

2 个答案:

答案 0 :(得分:3)

按字面解释问题的标题:RequireJS can turn object literals directly into AMD modules,例如:

define({
  getName: function() {
    return 'this is a test3';
  },
  name: 'test'
})

但是,使用这种模式,一个属性不可能引用它的“邻居”(但这是JS对象文字语法的限制,而不是RequireJS本身)。

答案 1 :(得分:1)

我试过了我的一面。试试这个:

define([], function () {
  var _name = 'this is a test3';
  var returnedModule3 = function(){
    this.name = 'test';
    this.getName = getName
  }
  function getName() {
    return _name;
  }
  return returnedModule3;    
});

注意this应附加到returnedModule3中的每个属性,以便从外部/其他JS文件访问,否则它将变为私有功能,您将获得错误object has no method getName

您的代码问题:在您的代码中,您尝试创建对象实例。

另一种方法(出口对象): 如果您要导出Object,就像returnedModule3一样,那么必须将main.js定义为:

require(['module3'], function(module3ref){
  // do something with the loaded modules
  console.log("module3.getName:"+module3ref.getName());
});
相关问题