作为参数传递时无法设置module.exports

马蒂亚斯·西塞罗(Matias Cicero)

我正在使用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,因为mmodule指向同一对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章