2016-07-14 85 views
0

我需要理解Node.js中範圍的概念。事實上,this === global,當我嘗試以下Node.js中模塊的範圍

//basic1.js file 
this.bar = "Bacon"; 


//basic2.js file 
require('./basic1'); 
console.log(this.bar); 

和運行basic2.js代碼,輸出是不確定的,而不是培根。由於我在全局對象中分配屬性欄,並且由於全局對象由所有節點模塊共享,爲什麼我將未定義爲輸出?你能幫我理解嗎?

+0

你怎麼斷定'這=== global'? – robertklep

+0

this === global // true –

+0

您是在REPL中測試它嗎?它不適用於文件。 – robertklep

回答

0

要了解Node.js的如何解釋模塊更好看source code

  1. 讀取源代碼文件。
  2. 將函數調用包裝到函數調用中,如function(exports, require, module, __dirname, __filename){ /* source code */ }
  3. 評估包裝好的代碼到v8虛擬機中(類似於瀏覽器中的eval函數)並獲取函數。
  4. 從上一步調用函數與覆蓋this上下文與exports

簡化代碼:

var code = fs.readFileSync('./module.js', 'utf-8'); 
var wrappedCode = `function (exports, require, module, __dirname, __filename) {\n${code}\n}`; 
var exports = {}; 
var fn = vm.runInThisContext(wrappedCode); 
var otherArgs = []; 
// ... put require, module, __dirname, __filename in otherArgs 
fn.call(exports, exports, ...otherArgs);