18

私はいつも JSLint を使用していますが、ちょうど今日、見たことのないエラーに遭遇しました。次のコードを使用すると、次のエラーが表示されます。

try {

  document.execCommand('BackgroundImageCache', false, true);

} catch (ex) {}

エラー:

Expected 'ignore' and instead saw 'ex'.
} catch (ex) {}

そこで、コードを次のように変更すると、エラーはなくなりました。

try {

  document.execCommand('BackgroundImageCache', false, true);

} catch (ignore) {}

これでエラーが修正される理由について、インターネット上で説明が見つかりません。何が起きているのか、なぜこれで問題が解決したのか誰か知っていますか?

ありがとうございました。

4

1 に答える 1

31

I think you're right -- jslint didn't used to complain like this. Instead, it told you that you needed to do something with ex, right? I'll check github to see and edit this later. EDIT: Great catch [by you]! Crockford, JSLint's author, added this on April 29th of this year around line 3444. And he uses empty catch blocks in jslint's source, so I guess he has to give us the kludge too. ;^)

JSLint wants you to kludge empty catch blocks with ignore as the variable name so that it's obvious to people reading your code that you intentionally meant not to do anything in your catch block. As Crockford says elsewhere, he feels that, "It is difficult to write correct programs while using idioms that are hard to distinguish from obvious errors."

1.) ex used (okay)

So (as I'm guessing you know) if you write this code and do something with ex, jslint doesn't complain.

/*jslint browser: true, white:true, sloppy:true*/

var spam;

try {
    spam = "spam";
} catch (ex) {
    window.alert(ex);
}

2.) ex unused means ignore (okay too)

So if you mean not to do anything with ex, he wants the code to tell folks you didn't screw up by leaving your ex equivalent in there by naming that variable ignore.

/*jslint browser: true, white:true, sloppy:true*/

var spam;

try {
    spam = "spam";
} catch (ignore) {
}

3.) ignore used (error!)

So, in typical Crockfordian fashion, you now can't use ignore and actually do something in the catch block!

/*jslint browser: true, white:true, sloppy:true*/

var spam;

try {
    spam = "spam";
} catch (ignore) {
    window.alert(ignore);
}

That gives

Unexpected 'ignore'. } catch (ignore) {

Just another hyper-explicit "don't make code that looks like an error" move by Crockford.

(Aside: Might be fun to take a look at Why are empty catch blocks a bad idea while you're on the subject. Honestly, though ignore is probably a useful convention, based on that discussion (I mean, it includes Skeet arguing against empty catch blocks!), I'm a little surprised Crockford allows the ignore kludge, as the above link has arguments that feel a lot like his for calling some regular expressions "unsafe".)

于 2013-05-18T16:56:41.630 に答える