簡體   English   中英

異常的node.js行為

[英]Unusual node.js behavior

今天,我看到了這段代碼,該代碼在node.js環境中運行。 (> node.exe test.js)

var param = (typeof module !== "undefined" && module.exports) || {};

(function(exports){

   console.log(exports === module.exports);

})(param);

並且此日志返回true。

有人可以向我解釋這種行為嗎?

提前致謝。

如果module沒有未定義(它不是因為它是默認的對象),並module.exports是truthy的事情(這是默認設置),然后exports被分配到param並傳遞給函數。

exports然后比較module.exports ,和他們是一樣的,因為module.exports是對象從在第一時間就來了。

exports將與module.exports如果它在其他地方運行(例如,在瀏覽器中獲取window而不是module ),因為{}會被分配給param 。)


更新關於該問題的評論:

嗯,也許是錯誤的,但是我認為(((typeof module ..)|| {})將返回true,但不會返回“ exports”對象

否。 &&將(從左到右工作)評估為它測試的第一個虛假事物,或者(如果一切都是真實的)評估為它測試的最后一個真實事物。

typeof module !== "undefined"為true,因此它測試module.exports ,也為true,因此它返回module.exports

||返回它測試的第一個真實或最后一個虛假的東西,因此它隨后返回module.exports

var d = (a && b) || c

如果a為真,則d求值為b 如果a為假,則d求值為c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM