简体   繁体   English

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

[英]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 ,因为mmodule指向同一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM