JSLint 抱怨我的 try/catch
javascript,当通过 JSLint 运行时,会对我大喊大叫,我不知道为什么。
/*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();
它告诉我:
第 12 行第 11 行字符出现问题:“e”已定义。
} catch(e) {
我似乎对第二个 catch(e)
感到不安。为什么这会成为一个问题?它不是简单地将 e 设置为 catch 块内的局部变量吗?我是否需要为函数中所有捕获的错误指定局部变量的唯一名称?
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();
It tells me:
Problem at line 12 character 11: 'e' is already defined.
} catch(e) {
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于 JSLint,
try..catch
具有将e
声明为局部变量的隐式效果。因为同一个函数中有两个这样的块(JavaScript 中没有块作用域),所以 JSLint 将其视为声明一个已经声明的变量。将变量命名为
e1
、e2
、等 将防止 JSLint 发出此警告。但这真的是个问题吗? ECMAScript 5 规范第 12.14 节指出,“无论控制如何离开块,词法环境总是恢复到之前的状态。”事实上,情况似乎确实如此:因此,总而言之,这只是 JSLint 的一个限制,不太可能导致任何实际问题。
To JSLint,
try..catch
has the implicit effect of declaringe
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.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:So, to conclude, this is simply a limitation of JSLint and is unlikely to lead to any practical problem.
尝试使用不同的变量,可能会感到困惑,因为 e 通常是为事件处理程序保留的。
Try to use a different variable, maybe its getting confused because e is usually reserved for event handlers.
我使用的 JSLint 根本没有显示任何错误 - 并且逻辑上您的代码是正确的。
The JSLint I use shows no error at all - and logical your code is correct.
JSLint 在这里可能就是错误的。根据 ECMAScript 规范,输入
catch
块会创建一个新的作用域,在该作用域内定义异常变量。在您的示例中,e
仅在catch
块内部有效,并且不在外部定义。这里没有重新定义。JSLint might simply be wrong here. According to the ECMAScript spec, entering a
catch
block creates a new scope inside which the exception variable is defined. In your example,e
is valid only inside thecatch
block and is not defined outside. There is no redefinition here.为每个 try / catch 使用不同的变量。
Use a different variable for each try / catch.