Node和Chrome中的块范围内的const(V8) [英] const within block scopes in Node and Chrome (V8)

查看:117
本文介绍了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

我调查了从 MSN - 块范围了解 var 在javascript中没有块范围。展望未来, MSN - const 描述了一个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:


常量是块作用域的,就像使用let语句定义的变量一样。常量的值不能通过重新赋值而改变,并且不能重新声明。

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

在这种情况下,我会说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


这个声明创建了一个常量,它可以是声明它的函数的全局变量或局部变量。

This declaration creates a constant that can be either global or local to the function in which it is declared.

这是否意味着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 指令以启用此行为。最新版本已更改: http://v8project.blogspot.ru/2016/01/v8 -release-49.html

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

引用:


发布4.9还使块级构造如类和在严格模式之外可用

Release 4.9 also makes block level constructs such as class and let available outside of strict mode

这也适用于 const

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆