Is the 'catch' method name of JS Promises/

2020-02-07 02:30发布

问题:

I started to use JS Promises in a project recently. I noticed that every time I use .catch my JS linter complains. It does run and does what it should but I looked up the ECMAScript spec and it really looks like it is right: Since catch is a keyword it can not be used as an identifier. As I understand method names are identifiers, so this is invalid:

Promise.reject("Duh").catch(alert);

It should be this instead:

Promise.reject("Duh")['catch'](alert);

What am I missing?

回答1:

What am I missing?

A property name is not an identifier, it can use any identifier name. From the spec on Property Accessors:

MemberExpression : MemberExpression . IdentifierName
CallExpression : CallExpression . IdentifierName

and identifiers:

Identifier :: IdentifierName but not ReservedWord

You can use any arbitrary identifer name (but not things like integers) in a dot property access, but you can't use those that are [reserved] keywords as identifier, e.g. in a variable or function name.

However, this did change with ES5, back in EcmaScript 3 property names were required to be identiers. That's why you still need to use the bracket notation for keywords if you want to support legacy browsers; and it's the reason why your linter complains about it. Same holds for property names in object literals.