[英]Expressjs JavaScript Fundamentals: exports = module.exports = createApplication;
我不知道這個模式叫什么,如果我這樣做,我會直接查找。
主要是,這是如何工作的? (此代碼取自Express.js)
exports = module.exports = createApplication;
在有這種類型的引用變量鏈ex之前我見過類似的模式:
x = y = z
我理解export vs module.exports,但是看看上面的模式讓我對它的實際工作方式提出質疑。
我按照一般的經驗法則說'module.exports'是真正的交易,'exports'是它的幫手,更多關於這里
模塊模式是這樣的(不改變module.exports)嗎?
exports = module.exports = {};
例如:
exports.name = 'hello'
結果
exports = module.exports = {name: 'hello'}
更改出口參考時會發生什么?
exports = {name: 'bob'}
現在當你添加到導出時,它將引用`{name:'bob'}並且不再與module.exports有任何聯系?
你的直覺是正確的。 我會自下而上地工作:
在運行任何文件之前,Node.js 將整個腳本包裝在一個立即調用的函數表達式(IIFE)中 :
(function (exports, require, module, __filename, __dirname) {
// ...script goes here...
});
這就是它如何引入module
並將變量exports
到范圍中; 它們並不比函數參數更特殊。
exports
module.exports
上的Node.js文檔和exports
別名非常有用。 首先, module.exports
和exports
變量都引用模塊系統創建的同一個空對象。
如果一個模塊只需要一個普通的舊JavaScript對象導出一些屬性進行設置, exports
是所有的需要:
exports.get = function(key) {
// ...
};
exports.set = function(key, value) {
// ...
};
當代碼require()
s這個模塊時,結果將類似於:
{
get: [Function],
set: [Function]
}
module.exports
但是,Express createApplication
構造函數createApplication
作為根值createApplication
。 要導出函數本身,而不是僅將其分配給導出對象上的屬性,它必須首先完全替換導出的對象:
module.exports = createApplication;
現在, exports
尚未更新,仍然引用舊對象,而module.exports
是對createApplication
的引用。 但是如果你繼續閱讀 ,你會發現除了構造函數之外,Express還會導出其他幾個屬性。 雖然將這些屬性分配給module.exports
的新值就module.exports
,但是重新分配exports
以使它再次成為module.exports
的別名,然后在exports
上分配這些屬性,這相當於分配它們。在module.exports
。
因此,這些示例在功能上是等效的:
module.exports = createApplication;
function createApplication() {
// ...
}
module.exports.application = proto;
module.exports.request = req;
module.exports.response = res;
但這個不那么冗長:
exports = module.exports = createApplication;
function createApplication() {
// ...
}
exports.application = proto;
exports.request = req;
exports.response = res;
無論哪種方式,結果都是相同的,在根上名為createApplication
的函數,其上有可用的屬性:
{
[Function: createApplication]
application: [Object],
request: [Object],
response: [Object],
// ...a few other properties...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.