2016-03-04 48 views
4

我在使用Browserify構建我的包。傳遞參數時無法設置module.exports

我有以下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); 

爲什麼會出現這種情況,這是爲什麼需要?

+0

爲什麼不簡單地返回'Service'並且從iife的結果中分配'exports'? –

回答

2

在您的第一個示例中,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); 

mmodule,當我們設置m.exports,我們設置module.exports,因爲mmodule指向同一個對象。