我正在尝试使用 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;
});
这周围有没有?
就像你在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 文档建议像在上一个代码段中那样做:只需返回分配给module.exports
的值。