为什么Chrome在“严格模式”下使用块内的函数时仍然保持沉默?

我对JS "strict mode";很新颖"strict mode"; ,当我使用代码如:

 function outer(){ "use strict"; var ctype; function inner(){ if(ctype!=undefined){ function hello1(){ console.log("hello1"); } hello1() }else { function hello2(){ console.log("hello2"); } hello2(); } } return inner; } var inner = outer(); inner(); 

我想知道为什么Chrome(版本49)没有提供任何错误,但是Node.js可以给出“ SyntaxError:在严格模式代码中,函数只能在顶层声明或者在其他函数中立即声明 ”。

此表指出,我的Chrome应该报告错误。

您使用的Node.js版本(0.12.9)使用V8 JavaScript引擎(3.28.71.19)的旧版本,它不遵循ECMAScript 6中添加的新函数声明范围规则。您的Chrome版本重新使用(49)使用新版本的V8(4.9.385),它支持新规则,至less在严格模式下。

在ECMAScript 6之前,函数声明将被限定为包含函数。 例如:

ECMAScript 5

 function main() { if (true) { function example() {}; console.log(example); // function example() {} } console.log(example); // function example() {} } 

这被认为是令人困惑的行为,所以在严格模式下被禁止,导致您在Node中看到的错误。

在ECMAScript 6中,函数声明的范围是最接近的块。 块是两个括号( { ... } )之间包含的任何一系列语句,例如if语句之后。

ECMAScript 6

 function main() { 'use strict'; if (true) { function example() {}; console.log(example); // function example() {} } console.log(example); // ReferenceError: example is not defined } 

这种行为更有意思,更不容易混淆,所以在严格模式下是允许的。

但是,testing这有点令人困惑,因为Chrome目前只能在严格模式下启用一些ES6规则。