【问题标题】:Export a constructor from a CommonJS style module in RequireJS从 RequireJS 中的 CommonJS 样式模块导出构造函数
【发布时间】:2015-02-03 12:41:43
【问题描述】:

我正在尝试使用 CommonJS 样式模块中的 exports 对象导出构造函数。出于某种原因,需要该模块会导致返回一个空对象,而不是导出的函数。

比如这个模块;

define(function(require, exports) {
    var Example = function() {
        this.example = true;
    };

    exports = Example;
});

当另一个模块需要它并被实例化时,会导致Uncaught TypeError: object is not a function 错误。

define(function(require, exports) {
    var Example = require('example');
    var example = new Example();
});

但是,如果我修改模块以返回构造函数而不是使用导出对象,那么一切都会按预期工作。

define(function(require, exports) {
    var Example = function() {
        this.example = true;
    };

    return Example;
});

这里面还有吗?

【问题讨论】:

    标签: javascript requirejs commonjs


    【解决方案1】:

    就像您在 Node.js 中所做的那样,您必须分配给 module.exports 而不是 exports 本身。所以:

    define(function(require, exports, module) {
        var Example = function() {
            this.example = true;
        };
    
        module.exports = Example;
    });
    

    分配给exports 不起作用,因为exports 是您的函数的本地变量。函数之外的任何东西都无法知道您已分配给它。当您分配给module.exports。这是另一回事,因为您正在修改 module 所引用的 object

    RequireJS 文档 suggests 就像您在上一个 sn-p 中所做的那样:只需返回您分配给 module.exports 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2017-10-27
      • 2018-06-22
      • 1970-01-01
      • 2018-04-13
      相关资源
      最近更新 更多