the*_*v19 3 javascript error-handling scope var try-catch
我正在使用 JavaScript 中的 try-catch 块,并且遇到了一些我不完全理解的变量作用域行为。
我知道console.log(boo)打印20到控制台是因为变量已经用var关键字声明了,因此它是功能范围的(即不是块范围到 catch 块)。
但是,我不明白为什么err变量的范围也不与变量相同boo。因此我不明白为什么它undefined在 catch 块之外。
(function() {
try {
throw new Error();
} catch (err) {
var err = 10;
var boo = 20;
console.log(err); //'10' (as I expect)
}
// Why doesn’t this log '10' ???
console.log(err); // 'undefined' (but I expected '10')
console.log(boo); // '20' (as I expect)
})();Run Code Online (Sandbox Code Playgroud)
当var将符号提升到功能块的顶部时,catch 子句的“参数”对于子句来说是本地的。由于您将提升值命名为与子句符号相同,因此这可能会相当混乱。本质上,您的代码与以下内容相同:
(function () {\nvar err;\nvar boo;\ntry {\n throw new Error();\n } catch (err) {\n err = 10; // Set the catch\'s "local" `err` identifier to `10`\n boo = 20; // Set the hoisted `boo` identifier to `20`\n console.log(err);\n }\n console.log(err); // The hoisted `err` was never set.\n console.log(boo); // \xe2\x80\x9920\xe2\x80\x99 (as I expect)\n})();\nRun Code Online (Sandbox Code Playgroud)\n\n您可能还认为errcatch 子句中的 the 就像函数/子句的参数;它的作用域是函数的局部作用域,与全局作用域无关(无论该符号是否存在于全局作用域中)。
| 归档时间: |
|
| 查看次数: |
228 次 |
| 最近记录: |