我正在使用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
指向同一对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句