我正在使用 Browserify 构建我的包.
我有以下 service.js
:
(function (exports, require) {
// ...
var Service = function (name, region) {
this.name = name;
this.region = region;
// ...
}
exports = Service;
})(module.exports, require);
每当我尝试在另一个模块上require('./service')
时,我都会得到一个空对象,就好像从未设置过exports
对象一样。
如果我在没有参数封装的情况下使用 module.exports
,一切正常:
(function (require) {
// ...
var Service = function (name, region) {
this.name = name;
this.region = region;
// ...
}
module.exports = Service;
})(require);
为什么会发生这种情况以及为什么需要这样做?
最佳答案
在您的第一个示例中,example
是匿名函数范围内的变量,它指向 module.exports
。当您说 exports = Service
时,您正在更改 exports
指向的内容,而不是 module.exports
指向。
当您说 module.exports = Service
时,您正在更改 module
的属性,该属性是全局范围的。
补充说明:
(function (m, require) {
// ...
var Service = function (name, region) {
this.name = name;
this.region = region;
// ...
}
m.exports = Service;
})(module, require);
m
指向 module
,当我们设置 m.exports
时,我们正在设置 module.exports
,因为 m
和 module
指向同一个对象。
关于javascript - 作为参数传入时无法设置 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800802/