[英]When should I use try/catch instead of functions to declare non global variables in JavaScript?
考虑以下代码:
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功能。
好吧,有一个区别: 为什么catch子句具有自己的词汇环境?
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);
在EcmaScript 5中,Traceur编译器可以为单个变量创建词法环境,这基本上是黑客的行为,可能是Google也优化了其浏览器以识别这种模式,这解释了为什么它在Chrome上非常快。
在手动编写的代码中,这绝对不是一个好习惯-没有注释,没人知道它的作用。 使用IEFE以获得可读性。
这似乎是一个非常糟糕的做法。
异常通常会减慢执行速度,并使系统引发错误然后再使用error变量是过分的
。 更新:对我来说,这有点令人震惊:在Chrome中使用try-catch时,代码看起来更快,但是在Firefox中却慢一些,而在IE 10中则慢一些:这是我刚刚创建的测试 。
无论如何,我认为正确的方法是使用这样的IIEF:
(function () {
var someVariable=...
...
})();
更优雅。 另一个区别是只有错误的变量是局部变量,在catch块上创建的任何其他变量都是全局变量。
如果操作可能导致某些错误(IOException,...),则应使用try / catch。 如果尝试中有错误,它将执行捕获的操作。 如果不可能出错,请使用功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.