语法错误:"x" 是保留标识符

当使用 保留关键字 作为标识符时,会发生 JavaScript 异常 "变量是保留标识符"。

¥The JavaScript exception "variable is a reserved identifier" occurs when reserved keywords are used as identifiers.

信息

¥Message

SyntaxError: Unexpected reserved word (V8-based)
SyntaxError: implements is a reserved identifier (Firefox)
SyntaxError: Cannot use the reserved word 'implements' as a variable name. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

如果将它们用作标识符,则会抛出 保留关键字。这些在严格模式和宽松模式下保留:

¥Reserved keywords will throw in if they are used as identifiers. These are reserved in strict mode and sloppy mode:

  • enum

以下仅当在严格模式代码中找到时才保留:

¥The following are only reserved when they are found in strict mode code:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static

示例

¥Examples

严格和非严格保留关键字

¥Strict and non-strict reserved keywords

enum 标识符通常被保留。

¥The enum identifier is generally reserved.

js
const enum = { RED: 0, GREEN: 1, BLUE: 2 };
// SyntaxError: enum is a reserved identifier

在严格模式代码中,保留了更多的标识符。

¥In strict mode code, more identifiers are reserved.

js
"use strict";
const package = ["potatoes", "rice", "fries"];
// SyntaxError: package is a reserved identifier

你需要重命名这些变量。

¥You'll need to rename these variables.

js
const colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
const list = ["potatoes", "rice", "fries"];

更新旧版浏览器

¥Update older browsers

例如,如果你使用的是尚未实现 letclass 的较旧浏览器,则应更新到支持这些新语言功能的更新浏览器版本。

¥If you are using an older browser that does not yet implement let or class, for example, you should update to a more recent browser version that does support these new language features.

js
"use strict";
class DocArchiver {}

// SyntaxError: class is a reserved identifier
// (throws in older browsers only, e.g. Firefox 44 and older)

也可以看看

¥See also