2012-05-08 78 views
1

那是什麼這個工程的原因:Node.js的模塊出口

exports.foo = 'foo'; 

var bar = require('./foo'); 
console.log(bar); // {foo: 'foo'} 

但這並不:

var data = { foo: 'foo' }; 
exports = data; 

var bar = require('./foo'); 
console.log(bar); // {} 
// expected {foo: 'foo'} 

回答

1

那麼,在第二個代碼,你基本上覆蓋出口對象。所以,即使你的代碼能夠工作,我猜所有其他的輸出也會被銷燬(覆蓋)。因此,節點可能有一些保護機制來避免這種情況

3

您可以通過將exports = data;替換爲module.exports = data;來修復第二個代碼。

前者不起作用的原因是它只在模塊名稱空間中分配給exports另一個對象。後者用data對象替換module對象上exports屬性的值。

5

我會試着回答這是一個JavaScript的問題 代碼示例

function a() {} 
a.prototype.foo = {test:"bar"} 
var d = new a(); 
var c = new a(); 
console.log(d.prototype ==== c.prototype) // Both c and d share the same prototype object 
d.foo.hai = "hello" 
console.log(d.prototype ==== c.prototype) // Still the they refer to the same 
d.foo = {im: "sorry"} 
console.log(d.prototype ==== c.prototype) // now they don't 

同爲節點

console.log(module.exports === exports);// true; They refer to the same object 
exports.a = {tamil: "selvan"} 
console.log(module.exports === exports);// true even now 

exports = {sorry: "im leaving"}; // overrides modules.exports 
console.log(module.exports === exports); //false now they don't 
console.log(module.exports); // {a: {tamil: "selvan"}} 
console.log(exports); // {sorry: "im leaving"} 

出口和module.exports指的是相同的核心對象,直到你重寫如在javsacript原型對象中。您覆蓋參考更改的那一刻。

module.exports = {something: "works"} 工作原理是因爲您正在更改節點在緩存時關注的模塊的屬性。

即使對於上述

module.exports === exports //is false they are no more the same

這證明反之也是如此:)

一件事module是參考當前的模塊所以總是喜歡用module.exportsexports