2016-03-06 67 views
2

當我通過一些another question on this topic:Nodejs導出和module.exports:爲什麼我們需要導出?

通過一些答案閱讀我(猜)瞭解什麼出口和module.exports是,以及如何使用它們!

我不明白的是,爲什麼我們需要出口無論如何,因爲我們能夠很好地解決這些事情只使用module.exports。此外,如果我認爲它很好:出口有潛力造成錯誤。

例如:

// feature.js 
function Person(name) { 
    this.name = name; 
    this.greet = function() { 
     console.log('Hi, my name is ' + this.name); 
    } 
} 
module.exports = Person; 

// app.js 
var Person = require(./feature); 

var Aron = new Person('Aron'); 
Aron.greet(); // Hi, my name is Aron 

您可以簡單地取消使用出口這個工作版本:

exports = Person; // wont' work 
exports.Person = Person; // still won't work (until you resolve it as new Person.Person('Aron') or ..require(..).Person) Which is not readable.. 

爲什麼我們的出口呢?有人可以向我解釋使用導出而不是module.exports的好處嗎?

感謝提前!

回答

6

如果您只是將屬性添加到module.exportsexports,那麼您可以修改其中一個並獲得相同的結果。這是因爲module.exportsexports最初都指向完全相同的對象。所以,如果你修改一個,另一個指向同一個對象,所以這個改變將在任何一箇中看到。 exports顯然只是作爲打字快捷鍵提供的,因此您不必參考module.exports

所以,這是絕對安全:

exports.foo = 123; 

或者

module.exports.foo = 123; 

創建兩個完全相同的結果,並且都是安全的,因爲它們都只是一個屬性分配給同一個對象。

但是,如果您正在創建並分配一個全新的導出對象,那麼您必須將該對象分配給module.exports。只將它分配給exports對你沒有任何好處。

語法:

exports = module.exports = {foo: 1}; 

使得完全確保沒有錯誤是在這方面取得了和可能是爲什麼建議。

我不明白的是,爲什麼我們需要exports無論如何,因爲我們可以 完美工作的事情了只使用module.exports

只要你的代碼永遠不會使用exports,你可以只使用module.exports,從不擔心exports。你不需要exports。這很可能是爲了方便而提供的,但正如您已經發現便利可能會導致錯誤使用時的錯誤。

爲什麼我們有出口呢?有人可以向我解釋使用導出而不是module.exports的好處 嗎?

exports可能只是作爲打字便利而提供的。使用exports而不是module.exports的唯一好處是打字少一點,可能是一個小小的性能差異,因爲有一個較少的屬性查找。我個人只是假裝exports不存在,我從來沒有使用它。我邏輯上認爲module.exports是出口的真實位置,所以我只是在那裏分配或修改,從來沒有這樣做的問題。


下面是更長的解釋。

當一個模塊初始化時,它被包裹,看起來像這樣的一個函數裏:

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js 
    module.exports = '123; 
}); 

這是哪裏的moduleexports的定義從何而來。默認情況下,module.exports === exports當這個函數第一次執行時,你的模塊代碼開始運行。但是,exports在這裏只是一個方便。真正的出口在module.exports中。所以,如果你只是這樣做:

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js 
    exports = {foo: 123}; 
}); 

這最終沒有做任何事情,因爲module.exports不會在所有受到影響,這就是真正的出口。但是,如果你這樣做:

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js 
    module.exports = {foo: 123}; 
}); 

然後,實際出口確實修改,你的模塊將正常工作,但只要你執行module.exports = {foo: 123};,你所做module.exports指向新的對象和它現在將指向與exports指向的不同對象。所以,總的安全,有些人建議你這樣做:

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js 
    exports = module.exports = {foo: 123}; 
}); 

然後,既exportsmodule.exports相同的對象總是指向。


如果你不需要單獨使用exports,那麼你永遠不要需要分配什麼它,你可以這樣做:

module.exports = {foo: 123}; 

,還有會不惜一切沒有問題。但是,如果您已更改module.exports指向的對象,則必須確保沒有代碼實際上僅使用exports

+0

非常感謝您的詳細解答!這絕對清除了我! – Mar

相關問題