const within block scopes in Node and Chrome (V8)

2019-02-24 08:42发布

问题:

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);

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

0
1
2
99

However, Node (and Chrome) give me

0
0
0
99

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:

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.

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.

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?

回答1:

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

Quote:

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

This should also apply to const



回答2:

Chrome does not support ES6 by default. That const behavior you are citing is from ES6 specification.

That strange const behavior in Chrome is non standard, neither in ES5 (that has no such feature at all) nor in ES6.

It is failing basic tests: https://kangax.github.io/compat-table/es6/

const must have local, block scope.