Javascript 作为参数传入时无法设置module.exports
我正在使用 我有以下Javascript 作为参数传入时无法设置module.exports,javascript,browserify,commonjs,Javascript,Browserify,Commonjs,我正在使用 我有以下service.js: (function (exports, require) { // ... var Service = function (name, region) { this.name = name; this.region = region; // ... } exports = Service; })(module.exports, require); 每当
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);
为什么会发生这种情况以及为什么需要这样做?在第一个示例中,
示例
是匿名函数中的一个变量,它指向模块.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
指向同一个对象。为什么不直接从iife的结果返回服务
并分配导出
?