no-reserved-keys

不允许不带引号的保留字作为对象字面中的属性名称。

¥Disallows unquoted reserved words as property names in object literals.

ECMAScript 3 描述为一系列关键字和保留字,例如 ifpublic,用于或打算用于核心语言功能。规范还指出,这些关键字和保留字如果不包含在字符串中,就不能用作对象属性名称。当你在对象字面中使用关键字或保留字时,ECMAScript 3 环境中会发生错误。例如:

¥ECMAScript 3 described as series of keywords and reserved words, such as if and public, that are used or intended to be used for a core language feature. The specification also indicated that these keywords and reserved words could not be used as object property names without being enclosed in strings. An error occurs in an ECMAScript 3 environment when you use a keyword or reserved word in an object literal. For example:

var values = {
    enum: ["red", "blue", "green"]  // throws an error in ECMAScript 3
}

在此代码中,enum 用作对象键,将在 ECMAScript 3 环境(例如 Internet Explorer 8)中引发错误。

¥In this code, enum is used as an object key and will throw an error in an ECMAScript 3 environment (such as Internet Explorer 8).

ECMAScript 5 放宽了限制,使得关键字和保留字可以用作对象键而不会导致错误。但是,任何需要在 ECMAScript 3 中运行的代码仍然需要避免使用关键字和保留字作为键。

¥ECMAScript 5 loosened the restriction such that keywords and reserved words can be used as object keys without causing an error. However, any code that needs to run in ECMAScript 3 still needs to avoid using keywords and reserved words as keys.

规则详情

¥Rule Details

此规则旨在消除使用 ECMAScript 3 关键字和保留字作为对象字面键。因此,只要对象键在 ECMAScript 3 环境中引发错误,它就会触发警告。

¥This rule is aimed at eliminating the use of ECMAScript 3 keywords and reserved words as object literal keys. As such, it warns whenever an object key would throw an error in an ECMAScript 3 environment.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

var superman = {
    class: "Superhero",
    private: "Clark Kent"
};

var values = {
    enum: ["red", "blue", "green"]
};

此规则的正确代码示例:

¥Examples of correct code for this rule:

var superman = {
    "class": "Superhero",
    "private": "Clark Kent"
};

var values = {
    "enum": ["red", "blue", "green"]
};

何时不使用

¥When Not To Use It

如果你的代码只会在 ECMAScript 5 或更高版本的环境中执行,那么你可以放心地关闭此规则。

¥If your code is only going to be executed in an ECMAScript 5 or higher environment, then you can safely leave this rule off.

版本

此规则是在 ESLint v0.8.0 中引入,并在 v1.0.0 中删除。

进阶读物