今天在閱讀lodash源碼的時候,發現如下代碼,略作分享:
1.代碼片段一
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
該代碼目的是檢測lodash運行環境是否爲node環境,以此來獲取全局變量。分析下它的代碼:
typeof global == 'object' && global && global.Object === Object && global;
這個就是當global滿足前三個條件時,返回該global全局變量。
有node環境的判斷,相應的就有瀏覽器環境的判斷:
2.代碼片段二
var freeGlobal = require('./_freeGlobal');
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
- 該代碼得到最終的全局變量。
- 這裏的self指的是
window.self
。MDN:指向當前window的一個引用。意思就是window啦。 var root = freeGlobal || freeSelf || Function('return this')();
這個裏面的Function('return this')()
就是一個匿名函數執行,即:(function(){return this})()
。返回當前環境的this引用。