问题描述
当通过运行的JavaScript对我而言,我不知道为什么。
The javascript, when run through JSLint yells at me and I am not sure why.
/*jslint browser: true, devel: true, evil: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true */
var foo = function() {
try {
console.log('foo');
} catch(e) {
alert(e);
}
try {
console.log('bar');
} catch(e) {
alert(e);
}
};
foo();
它告诉我:
} catch(e){
似乎令人不安,我有一个第二个 catch(e)
。为什么这是一个问题?它不是简单地将e设置为catch块内的局部变量?我需要为函数中的所有陷阱错误唯一地命名局部变量吗?
It appears to be upset that I have a second catch(e)
. Why would this be an issue? Does it not simply set e to local variable inside the catch block? Do I need to uniquely name the local variables for all trapped errors in a function?
推荐答案
对于JSLint, try..catch
具有将 e
声明为局部变量的隐含效果。因为在同一个函数中有两个这样的块(在JavaScript中没有块范围),所以JSLint看到声明已经被声明的变量。
To JSLint, try..catch
has the implicit effect of declaring e
as a local variable. Because you have two such blocks within the same function (there is no block scope in JavaScript), JSLint sees that as declaring a variable that has already been declared.
命名变量 e1
, e2
,等。来自JSLint的警告。这真的是一个问题吗? ECMAScript 5规范第12.14节说:无论控制如何离开Block,LexicalEnvironment总是恢复到原来的状态。这实际上似乎是这样的:
Naming the variables e1
, e2
, etc. would prevent this warning from JSLint. Is it really a problem though? The ECMAScript 5 specification, section 12.14, says "No matter how control leaves the Block the LexicalEnvironment is always restored to its former state." This, in fact, does appear to be the case:
try {
throw new Error("testing 1234");
} catch(fooBarBaz){
alert("Catch: " + fooBarBaz); // works
}
alert(fooBarBaz); // throws exception
所以,总而言之,这只是JSLint的一个限制并且不太可能导致任何实际问题。
So, to conclude, this is simply a limitation of JSLint and is unlikely to lead to any practical problem.
这篇关于JSLint抱怨我的try / catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!