美文网首页
try..catch

try..catch

作者: 没有昵_称 | 来源:发表于2020-07-16 09:56 被阅读0次

(function () {
try {
throw new Error();
} catch (x) {
var x = 1, y = 2;
console.log(x);
}
console.log(x);
console.log(y);
})();
输出结果:

1
undefined
2
我们都知道var是在预编译阶段会有一个变量提升,这种类型很容易解决,但是当遇到在catch(x)中与已有变量重名的情况,一定要区分两者之间的关系。

用变量提升的方法,把程序重写并分析如下:

(function () {
var x,y; // 外部变量提升
try {
throw new Error();
} catch (x/* 内部的x */) {
x = 1; //内部的x,和上面声明的x不是一回事!!
y = 2; //内部没有声明,作用域链向上找,外面的y
console.log(x); //当然是1
}
console.log(x); //只声明,未赋值,undefined
console.log(y); //就是2了
})();

相关文章

网友评论

      本文标题:try..catch

      本文链接:https://www.haomeiwen.com/subject/vwiwhktx.html