从RequireJS中的CommonJS样式模块导出构造函数

时间:2015-02-03 12:41:43

标签: javascript requirejs commonjs

我正在尝试使用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();
});

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

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

    return Example;
});

到底有没有?

1 个答案:

答案 0 :(得分:4)

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

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

    module.exports = Example;
});

分配给exports无效,因为exports是您的函数本地的变量。功能之外的任何内容都无法知道您已分配给它。当您分配到module.exports时。这是另一回事,因为您正在修改module引用的对象

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

相关问题