什么时候应该使用try / catch而不是函数来在JavaScript中声明非全局变量?

时间:2014-03-10 13:23:40

标签: javascript try-catch

请考虑以下代码:

try{
     throw undefined;
}
catch(someVariable){
    someVariable = 10;
    // do whatever you want with someVariable
    // someVariable will not be a global object at all. (without help of any function scope)
}
// someVariable is no longer valid here

为什么有些人在不想声明全局变量时会使用这种语法而不是函数?

附加说明:

我已经看过很多这种语法,但最重要的是Google traceur

try {
    throw undefined;
  } catch (a) {
    a = 10;
  }

它是由于以下ecma脚本6语法而生成的:

{
    let a = 10;
}

Google traceur 是旧版浏览器上的ECMA Script 6解析器,目前不支持新的JavaScript功能。

3 个答案:

答案 0 :(得分:2)

嗯,有区别:Why do catch clauses have their own lexical environment?

try {
     throw undefined;
} catch(someVariable) {
    someVariable = 10; // someVariable will not be global
    var someOtherVariable = 5; // but any declared 'var' will be
}
// someVariable is no longer valid here
console.log(someOtherVariable); // still 5

正如您所看到的,这与您使用

时的行为相同
{
    let someVariable = 10;
    var someOtherVariable = 5;
}
console.log(someVariable, someOtherVariable);

这基本上是Traceur转换器在EcmaScript 5中为单个变量创建词汇环境的黑客行为。可能谷歌还优化了他们的浏览器以识别这种模式,这解释了为什么它在Chrome上的速度非常快。

在手动编写的代码中,这绝对是一种不好的做法 - 没有评论,没有人知道这是做什么的。使用IEFE可读性。

答案 1 :(得分:1)

这似乎是一个非常糟糕的做法。例外通常会减慢执行速度,并使系统引发错误然后重新使用错误变量是 。 更新:对我来说这有点令人震惊:在Chrome中使用try-catch时代码似乎更快,但在Firefox中速度更慢,在IE 10中使用更慢: 这是我刚刚创建的test

无论如何,我认为正确的方法是使用这样的IIEF:

(function () {
    var someVariable=...
    ...
})();

它更优雅。另一个区别是只有变量,错误是本地的,在catch块上创建的任何其他变量都是全局的。

答案 2 :(得分:-1)

当操作可能导致某些错误(IOException,...)时,您应该使用try / catch。如果尝试中有错误,它将执行catch中的操作。如果没有错误使用功能的可能性。

相关问题