为什么 try/catch 块中的已定义变量在同一函数范围内显示为未定义?
Why is a defined variable in try/catch block showing undefined in the same function scope?
此代码是我正在学习的 javascript 课程的一部分。而这个练习是在我需要猜测输出的错误处理部分。
代码:
(function () {
try {
throw new Error();
} catch (err) {
var err = 5; //creating another local err variable
var boo = 10;
console.log(err);
}
console.log(err);
console.log(boo);
})();
输出:
5
undefined //I don't understand this part
10
错误在 catch 块中作为参数 err
传递。但是对于 var
,err
变量会被覆盖。因此,5
不是记录错误,而是在第一个 console.log(err)
.
中记录
但我想不通为什么第二个 console.log(err)
输出 undefined
。据我所知, var
不是块范围的,因此,在同一函数范围内,我应该可以访问 err
变量。而且,由于提升,var
最初变得未定义。但是由于 try/catch
块是 同步的 并且我在定义它之后记录变量, 它不应该记录 5
吗? 因为 console.log(boo)
按预期返回 10
。
是不是创建了与局部参数同名的变量?
注意:这是我关于 Whosebug 的第一个问题。所以请原谅任何错误!
你是对的 var
是函数作用域而不是块作用域,但是如果 var
声明与 catch 块绑定变量同名,则 catch 块有一个例外阴影 var
声明不会提升到函数范围。
规范的相关部分:
https://262.ecma-international.org/10.0/#prod-annexB-CatchParameter
The Block of a Catch clause may contain var declarations that bind a name that is also bound by the CatchParameter. At runtime, such bindings are instantiated in the VariableDeclarationEnvironment. They do not shadow the same-named bindings introduced by the CatchParameter and hence the Initializer for such var declarations will assign to the corresponding catch parameter rather than the var binding.
此代码是我正在学习的 javascript 课程的一部分。而这个练习是在我需要猜测输出的错误处理部分。
代码:
(function () {
try {
throw new Error();
} catch (err) {
var err = 5; //creating another local err variable
var boo = 10;
console.log(err);
}
console.log(err);
console.log(boo);
})();
输出:
5
undefined //I don't understand this part
10
错误在 catch 块中作为参数 err
传递。但是对于 var
,err
变量会被覆盖。因此,5
不是记录错误,而是在第一个 console.log(err)
.
但我想不通为什么第二个 console.log(err)
输出 undefined
。据我所知, var
不是块范围的,因此,在同一函数范围内,我应该可以访问 err
变量。而且,由于提升,var
最初变得未定义。但是由于 try/catch
块是 同步的 并且我在定义它之后记录变量, 它不应该记录 5
吗? 因为 console.log(boo)
按预期返回 10
。
是不是创建了与局部参数同名的变量?
注意:这是我关于 Whosebug 的第一个问题。所以请原谅任何错误!
你是对的 var
是函数作用域而不是块作用域,但是如果 var
声明与 catch 块绑定变量同名,则 catch 块有一个例外阴影 var
声明不会提升到函数范围。
规范的相关部分: https://262.ecma-international.org/10.0/#prod-annexB-CatchParameter
The Block of a Catch clause may contain var declarations that bind a name that is also bound by the CatchParameter. At runtime, such bindings are instantiated in the VariableDeclarationEnvironment. They do not shadow the same-named bindings introduced by the CatchParameter and hence the Initializer for such var declarations will assign to the corresponding catch parameter rather than the var binding.