方法名称是否无效

方法名称是否无效

本文介绍了JS Promises/A+ 的“catch"方法名称是否无效,因为它是一个 JS 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始在一个项目中使用 JS Promises.我注意到每次使用 .catch 我的 JS linter 都会抱怨.它确实运行并做了它应该做的事,但我查找了 ECMAScript 规范 和看起来确实是正确的:由于 catch 是关键字,不能用作标识符.据我所知,方法名称是标识符,所以这是无效的:

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);

应该是这样的:

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

我错过了什么?

推荐答案

属性名称不是标识符,它可以使用任何标识符名称.来自属性访问器的规范:

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

标识符:

Identifier :: IdentifierName but not ReservedWord

您可以在点属性访问中使用任意标识符名称(但不能使用整数之类的名称),但不能使用 [reserved] 关键字作为标识符,例如在变量或函数名中.

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.

然而,这在 ES5 中确实发生了变化,回到 EcmaScript 3 属性名称必须是标识符.这就是为什么如果您想支持旧版浏览器,您仍然需要对关键字使用括号表示法;这就是你的 linter 抱怨它的原因.同样适用对象字面量中的属性名称.

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.

这篇关于JS Promises/A+ 的“catch"方法名称是否无效,因为它是一个 JS 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:39