最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Difference between node.js and chrome in v8 - Stack Overflow

programmeradmin4浏览0评论

chrome version 49.0.2623.110 m

node 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

chrome version 49.0.2623.110 m

node 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

Share Improve this question edited Nov 29, 2018 at 16:46 pushkin 10.3k16 gold badges63 silver badges107 bronze badges asked Apr 4, 2016 at 16:39 Eu Insumi PruncEu Insumi Prunc 4811 gold badge5 silver badges8 bronze badges 1
  • 1 It has nothing to do with V8, but the way global scope works in Node, and in browsers (where the global scope is window). Try console logging this, and it should bee clear. – adeneo Commented Apr 4, 2016 at 16:44
Add a ment  | 

1 Answer 1

Reset to default 11

When a function is called without context (and you are running in non-strict mode) this defaults to the global object.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论