v8中node.js和chrome之间的区别 [英] Difference between node.js and chrome in v8
问题描述
chrome版本49.0.2623.110 m
chrome version 49.0.2623.110 m
节点v5.10.0
这是我的代码:
var a = 0;
(function() {
this.a = 1;
this.b = 2;
console.log(a);
} )();
console.log(a);
console.log(b);
chrome give
chrome gives
1
1
2
节点给出
0
0
2
为什么会这样?
谢谢
推荐答案
在没有上下文的情况下调用函数(并且您在非严格模式下运行)此
默认为全局对象。
When a function is called without context (and you are running in non-strict mode) this
defaults to the global object.
在浏览器中,源代码的顶层在全局上下文中运行,因此 this.a
,即 window.a
与在顶部的全局上下文中声明的 var a
相同。分配 this.a = 1
与分配 a = 1
相同。
In a browser the top-level of your source code runs in the global context, so this.a
, which is window.a
is the same as the var a
declared in the global context at the top. Assigning this.a = 1
is the same as assigning a = 1
.
在node.js中,每个JavaScript文件都有自己的模块上下文,它与全局上下文分开,因此 var a = 0;
没有创建全局,您使用 this.a = 1;
创建的全局将被模块自己的 a
隐藏。
In node.js each JavaScript file gets its own module context that is separate from the global context, so var a = 0;
is not creating a global, and the global you created with this.a = 1;
will be shadowed by the modules own a
.
这篇关于v8中node.js和chrome之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!