我有这个代码:
(function() {
var ex;
try {
throw new Error('blah');
} catch(ex) {
console.log('ex i here:', ex);
}
console.log('ex out here:', ex);
return 'hi';
})()
这个日志:
我在这里:错误('blah');
ex out here:undefined
为什么会这样?我认为由于悬挂,ex
将被设置在这个区域范围之外,所以它应该在ex out here
中可用。
我希望它的工作类似于for循环:
for (i=0; i<2; i++) {
}
console.log(i); // gives 2
你搞砸了一些东西。
定义为var
的变量具有函数范围。 catch
中的参数未被提升,它具有块范围(仅在该捕获部分中)。
正如您在此示例中所看到的那样:ab
被悬挂,然后可以在捕获部分外部访问。 ex2
在上下文之外不存在。
(function() {
var ex;
try {
throw new Error('blah');
} catch(ex2) {
var ab = 3;
console.log('ex is here:', ex2.message);
}
console.log(ab);
console.log(ex2);
console.log('ex out here:', ex);
return 'hi';
})()
在您的示例中,使用相同的名称创建了不同的变量,但范围不同。如果发生这种情况,则(在几乎所有语言中)使用上下文中的“最深”变量。如果你想在主题的catch之外接受错误,你可以:
(function() {
try {
throw new Error('blah');
} catch(ex2) {
var ex = ex2;
console.log('ex is here:', ex2.message);
}
console.log(ex.message);
return 'hi';
})()
此代码的行为与此类似
(function() {
var ex1;
try {
throw new Error('blah');
} catch(ex2) {
console.log('ex i here:', ex2);
}
console.log('ex out here:', ex1);
return 'hi';
})()
这是因为捕获中声明的前者仅在捕获范围内可见,更多信息visit
关于循环,在那些迭代中,js查找包含它的最近范围的变量“i”声明,在这种情况下是父节点,因此正在改变的变量“i”是在开始时声明的变量“i” de loop中没有变量声明。
当
try
块中抛出异常时,exception_var
(例如,e
中的catch (e)
)保持throw
语句指定的值。您可以使用此标识符来获取有关抛出的异常的信息。该标识符是catch
子句的本地标识符。也就是说,它是在输入catch
子句时创建的,并且在catch
子句完成执行后,标识符不再可用。