Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 作为参数传入时无法设置module.exports_Javascript_Browserify_Commonjs - Fatal编程技术网

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的结果返回
服务
并分配
导出