Node和Chrome中的块范围内的const

Node和Chrome中的块范围内的const

本文介绍了Node和Chrome中的块范围内的const(V8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个nodejs(v4.2.4)应用程序我遇到了一些奇怪的行为。

I am writing a nodejs (v4.2.4) app were I encountered some odd behaviour.

function A(number) {
 this.number = number;
}

for(var i = 0; i < 3; i++) {
  const a = new A(i);

  console.log(a.number);
}

const b = new A(99);
console.log(b.number);

我的直觉来自Java(和FireFox之一),输出应该是

My intuition, coming from Java (and the one of FireFox), is that the output should have been

0
1
2
99

然而,Node(和Chrome)给我

However, Node (and Chrome) give me

0
0
0
99

我调查了从了解 var 在javascript中没有块范围。展望未来,描述了一个const虽然声明具有块作用域:

I investigated and understood from MSN - block scope that var does not have block scope in javascript. Looking further, MSN - const describes a const declaration as having block scope though:

在这种情况下,我会说Node和Chrome(在这种情况下可能是V8)在块作用域中对 const 进行某种阴影处理。但是他们也写了

In that case I would say that Node and Chrome (in that case probably V8), have some kind of shady handling of const in block scopes. But they also write that

这是否意味着V8将每个 const 声明作为全局变量放置,而FireFox创建当地人?如此重要的事情是如何以不同的方式实现的呢?

Does that mean that V8 puts every const declaration as a global variable while FireFox creates a local one? How can it be that something crucial like that is implemented so differently?

推荐答案

v8需要 use strict 指令以启用此行为。最新版本已更改:

v8 requires use strict directive to enable this behaviour. This has changed in latest version: http://v8project.blogspot.ru/2016/01/v8-release-49.html

引用:

这也适用于 const

这篇关于Node和Chrome中的块范围内的const(V8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:39