我需要了解Node.js中范围的概念。当我尝试下面的代码时this === global
的事实
//basic1.js file
this.bar = "Bacon";
//basic2.js file
require('./basic1');
console.log(this.bar);
并运行basic2.js,输出是undefined而不是Bacon。由于我在全局对象中分配属性栏,并且所有节点模块共享全局对象,为什么我将未定义为输出?你能帮我理解一下吗?
答案 0 :(得分:0)
要了解node.js如何更好地解释模块以查看source code:
function(exports, require, module, __dirname, __filename){ /* source code */ }
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);