简体   繁体   English

v8中node.js和chrome之间的区别

[英]Difference between node.js and chrome in v8

chrome version 49.0.2623.110 m 铬版本49.0.2623.110米

node v5.10.0 节点v5.10.0

Here is my code: 这是我的代码:

var a = 0;

(function() {
    this.a = 1;
    this.b = 2;
    console.log(a);
} )();

console.log(a);
console.log(b);

chrome gives 铬给

1
1
2

node gives 节点给出

0
0
2

Why does that happen? 为什么会这样?

Thanks 谢谢

When a function is called without context (and you are running in non-strict mode) this defaults to the global object. 如果在没有上下文的情况下调用函数(并且您在非严格模式下运行), this默认为全局对象。

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. 在浏览器中,源代码的顶层在全局上下文中运行,因此this.awindow.a )与在顶部的全局上下文中声明的var a相同。 Assigning this.a = 1 is the same as assigning a = 1 . 分配this.a = 1与分配a = 1相同。

In node.js each JavaScript file gets its own module context that is separate from the global context, so var a = 0; 在node.js中,每个JavaScript文件都有自己的模块上下文,它与全局上下文分开,因此var a = 0; is not creating a global, and the global you created with this.a = 1; 没有创建一个全局,以及你用this.a = 1;创建的全局this.a = 1; will be shadowed by the modules own a . 将被模块拥有a阴影。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM