鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ 關(guān)于underscore源碼的一點疑問, 涉及node.js模塊化

關(guān)于underscore源碼的一點疑問, 涉及node.js模塊化

以下是源碼信息


  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for their old module API. If we're in
  // the browser, add `_` as a global object.
  // (`nodeType` is checked to ensure that `module`
  // and `exports` are not HTML elements.)
  if (typeof exports != 'undefined' && !exports.nodeType) {
    if (typeof module != 'undefined' && !module.nodeType && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

這段代碼應(yīng)該是針對在nodejs環(huán)境中將_的方法掛載到exports._上,但不太懂這段代碼具體邏輯:

  1. typeof exports != 'undefined' && !exports.nodeType 為什么不使用嚴(yán)格不等于!==或直接用隱式轉(zhuǎn)換exports && !exports.nodeType;

  2. exports.nodeTypemodule.nodeType 是什么?;

  3. exports = module.exports = _; 這行代碼如何理解?。

回答
編輯回答
念初

其實上面的英文注釋已經(jīng)解釋了許多
這段代碼是用于在nodejs環(huán)境中暴露_方法

//這里這個if else是為了確定當(dāng)前環(huán)境是node環(huán)境還是瀏覽器環(huán)境
//typeof exports的結(jié)果必然是String類型,因此不使用嚴(yán)格不等于也可以
//至于為什么不使用隱式轉(zhuǎn)換,應(yīng)該是為了代碼語義更明確,就是想判斷不是undefined類型(存疑)
if (typeof exports != 'undefined' && !exports.nodeType) { 
  //nodeType是為了確定該值不是html dom元素
  if (typeof module != 'undefined' && !module.nodeType && module.exports) {
    //node環(huán)境下exports = module.exports = {},exports是對module.exports的引用
    //module.exports = _ ,注意到_其實是個函數(shù)(這段代碼上面定義了)
    //這切斷了exports和module.exports的聯(lián)系,只能被module.exports輸出,不能被exports輸出
    //所以需要exports = module.exports,重新建立起 exports 對 module.exports 的引用
    exports = module.exports = _;
  } 
  //兼容對module.exports支持不好的舊的commonJS規(guī)范
  //引用的時候可以 var _ = require("underscore")._
  exports._ = _;
} else { 
  //瀏覽器環(huán)境,_方法掛載到window上
  root._ = _;
}
2017年1月15日 11:24