捕获声明中没有悬挂?

问题描述 投票:1回答:3

我有这个代码:

(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
javascript hoisting
3个回答
3
投票

你搞砸了一些东西。

定义为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';
})()

2
投票

此代码的行为与此类似

  (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中没有变量声明。


1
投票

来自try ... catch statement

try块中抛出异常时,exception_var(例如,e中的catch (e))保持throw语句指定的值。您可以使用此标识符来获取有关抛出的异常的信息。该标识符是catch子句的本地标识符。也就是说,它是在输入catch子句时创建的,并且在catch子句完成执行后,标识符不再可用。

© www.soinside.com 2019 - 2024. All rights reserved.