JSLint complaining about my try/catch

纵然是瞬间 提交于 2019-12-05 03:01:01

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.

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

So, to conclude, this is simply a limitation of JSLint and is unlikely to lead to any practical problem.

Try to use a different variable, maybe its getting confused because e is usually reserved for event handlers.

The JSLint I use shows no error at all - and logical your code is correct.

Use a different variable for each try / 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 the catch block and is not defined outside. There is no redefinition here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!