[英]module.exports cannot be set when passed in as argument
I am building my bundle using Browserify . 我正在使用Browserify构建我的包。
I have the following service.js
: 我有以下
service.js
:
(function (exports, require) {
// ...
var Service = function (name, region) {
this.name = name;
this.region = region;
// ...
}
exports = Service;
})(module.exports, require);
Whenever I try to require('./service')
on another module, I get an empty object as if the exports
object was never set. 每当我尝试在另一个模块上
require('./service')
时,我得到一个空对象,好像从未设置过exports
对象一样。
If I use module.exports
without the argument encapsulation, everything works fine: 如果我
module.exports
没有参数封装的情况下使用module.exports
,一切正常:
(function (require) {
// ...
var Service = function (name, region) {
this.name = name;
this.region = region;
// ...
}
module.exports = Service;
})(require);
Why does this happen and why is this required? 为什么会发生这种情况?为什么需要这样做?
In your first example, example
is a variable scoped within your anonymous function, and it's pointing to module.exports
. 在您的第一个示例中,
example
是您的匿名函数范围内的变量,它指向module.exports
。 When you say exports = Service
, you're changing what exports
is pointing to, not what module.exports
is pointing to. 当你说
exports = Service
,你正在改变exports
指向的内容,而不是module.exports
所指向的内容。
When you say module.exports = Service
, you're changing a property of module
, which is globally scoped. 当您说
module.exports = Service
,您正在更改module
的属性,该属性是全局范围的。
An additional illustration: 另外一个例子:
(function (m, require) {
// ...
var Service = function (name, region) {
this.name = name;
this.region = region;
// ...
}
m.exports = Service;
})(module, require);
m
points to module
, and when we set m.exports
, we're setting module.exports
, since m
and module
point to the same object. m
指向module
,当我们设置m.exports
,我们设置module.exports
,因为m
和module
指向同一个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.