[英]Why does redeclaring a function identifier within a try block throw a SyntaxError?
The following lines of JavaScript 以下几行JavaScript
try {
function _free() {}
var _free = 1;
} finally { }
result in the following error: 导致以下错误:
Uncaught SyntaxError: Identifier '_free' has already been declared
However, the following two blocks of JavaScript code don't: 但是,以下两个JavaScript代码块不会:
Without the try
block scope: 没有
try
块范围:
function _free() {} var _free = 1;
Within a function
scope: 在
function
范围内:
function a() { function _free() {} var _free = 1; }
But why? 但为什么?
(Testing environment: Chromium 61.0.3126.0) (测试环境:Chromium 61.0.3126.0)
因为块范围的函数声明是新的ES6特性并且是安全的(即在名称冲突上抛出错误,类似于let
和const
),但是其他情况(无论是程序员错误)都需要保持向后兼容并静默覆盖功能。
To expand on Bergis answer , there is a difference in how the code is interpreted in ES5 and ES6 since block-scoped function declarations were added. 为了扩展Bergis的答案 ,自从添加了块范围的函数声明以来,在ES5和ES6中如何解释代码是有区别的。
Input: 输入:
function test() {
try {
function _free() { }
var _free = 1;
} finally { }
}
Since ES5 does not support block-level functions, _free
is hoisted to the parent function: 由于ES5不支持块级函数,因此
_free
被提升到父函数:
function test() {
var _free = function _free() { }
try {
var _free = 1;
} finally { }
}
In ES6, the function is declared at block-level, and semantically equal to a let
/ const
declaration: 在ES6中,函数在块级声明,并在语义上等于
let
/ const
声明:
function test() {
try {
let _free = function _free() { }
var _free = 1;
} finally { }
}
This throws an error because var _free
tries to declare a variable which is already declared. 这会引发错误,因为
var _free
尝试声明已声明的变量。 For example, this throws in ES6 as well: 例如,这也引发了ES6:
let _free;
var _free = 1; // SyntaxError: Indentifier '_free' has already been declared
While this is fine: 这很好:
var _free;
var _free = 1; // No SyntaxError
Setting the value of the already declared identifier is fine: 设置已声明的标识符的值是正常的:
let _free;
_free = 1;
Therefore, to set the declared identifier _free
to 1, you need to skip the second declaration : 因此,要将声明的标识符
_free
设置为1,您需要跳过第二个声明 :
try {
function _free() { }
_free = 1;
} finally { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.