如下代码,按照常理,全局作用域下申明的变量会自动成为全局对象下的一个属性
var a = 2;
function foo(){
console.log(this.a);
}
foo();
但是这个代码在不同的执行方法下好像出现了不同的预期,入下图,直接node + file文件名执行发现找不到this.a
如右边的一步步走的话发现是能找到this.a的,这其中是否有什么不同?
如下代码,按照常理,全局作用域下申明的变量会自动成为全局对象下的一个属性
var a = 2;
function foo(){
console.log(this.a);
}
foo();
但是这个代码在不同的执行方法下好像出现了不同的预期,入下图,直接node + file文件名执行发现找不到this.a
如右边的一步步走的话发现是能找到this.a的,这其中是否有什么不同?
有意思的问题,查了一下资料:
http://stackoverflow.com/questions/19850234/node-js-variable-declaration-and-scope
It doesn't work in Node when using var because testContext is a local of the current module. You should reference it directly: console.log(testContext);.
When you don't type var, what happens is that testContext is now a global var in the entire Node process.
In Chrome (or any other browser - well, I'm unsure about oldIE...), it doesn't matter if you use var or not in your example, testContext will go to the global context, which is window.
By the way, the "global context" is the default this of function calls in JS.
但是在Node REPL中,为什么又和浏览器的行为类似了,这个我不太清楚,同求该答案。
5 回答4.8k 阅读✓ 已解决
4 回答2.5k 阅读✓ 已解决
2 回答1.7k 阅读✓ 已解决
5 回答1.9k 阅读
2 回答1.4k 阅读✓ 已解决
3 回答2k 阅读
1 回答3.2k 阅读
对于代码写在文件中的情况,其实一个文件就是一个 CommonJS 模块,node 会对该模块加一层包裹,因此,你上面的代码最终是变成下面这样进行运行的:
所以,很明显了,
var a = 2
并不是全局变量,如果用想访问全局变量的话最好是用global
。但是直接在控制台中运行的代码是不会进行模块包装的。