如果您只是將屬性添加到module.exports
或exports
,那麼您可以修改其中一個並獲得相同的結果。這是因爲module.exports
和exports
最初都指向完全相同的對象。所以,如果你修改一個,另一個指向同一個對象,所以這個改變將在任何一箇中看到。 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;
});
這是哪裏的module
和exports
的定義從何而來。默認情況下,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};
});
然後,既exports
和module.exports
相同的對象總是指向。
如果你不需要單獨使用exports
,那麼你永遠不要需要分配什麼它,你可以這樣做:
module.exports = {foo: 123};
,還有會不惜一切沒有問題。但是,如果您已更改module.exports
指向的對象,則必須確保沒有代碼實際上僅使用exports
。
非常感謝您的詳細解答!這絕對清除了我! – Mar