2016-07-14 154 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);