aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/reserved_identifier/index.html
blob: d99acf3fa8a5b7163760cb96ccdbe9b5241fb9dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
---
title: 'SyntaxError: "x" is a reserved identifier'
slug: Web/JavaScript/Reference/Errors/Reserved_identifier
tags:
  - JavaScript
  - 语法错误
  - 错误
translation_of: Web/JavaScript/Reference/Errors/Reserved_identifier
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="消息提示">消息提示</h2>

<pre class="syntaxbox">SyntaxError: "x" is a reserved identifier (Firefox)
SyntaxError: Unexpected reserved word (Chrome)</pre>

<h2 id="错误类型">错误类型</h2>

<p>{{jsxref("SyntaxError")}}</p>

<h2 id="哪里出错了?">哪里出错了?</h2>

<p><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">保留字</a> 用作标记符将会出错. 这些标记符在严格模式和非严格模式下保留:</p>

<ul>
 <li><code>enum</code></li>
</ul>

<p>以下标记符只会在严格模式下才作为保留字:</p>

<ul class="threecolumns">
 <li><code>implements</code></li>
 <li><code>interface</code></li>
 <li>{{jsxref("Statements/let", "let")}}</li>
 <li><code>package</code></li>
 <li><code>private</code></li>
 <li><code>protected</code></li>
 <li><code>public</code></li>
 <li><code>static</code></li>
</ul>

<h2 id="示例">示例</h2>

<h3 id="严格与非严格模式下的保留字">严格与非严格模式下的保留字</h3>

<p>在两种模式下,<code>enum</code> 标识符都会作为保留字。</p>

<pre class="brush: js example-bad">var enum = { RED: 0, GREEN: 1, BLUE: 2 };
// SyntaxError: enum is a reserved identifier
</pre>

<p>在严格模式下,会有更多的保留字。</p>

<pre class="brush: js example-bad">"use strict";
var package = ["potatoes", "rice", "fries"];
// SyntaxError: package is a reserved identifier
</pre>

<p>你需要对上述变量重新命名。</p>

<pre class="brush: js example-good">var colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
var list = ["potatoes", "rice", "fries"];</pre>

<h3 id="升级旧版本浏览器">升级旧版本浏览器</h3>

<p>假如你还在使用尚未支持 let 或 class 等特性的旧版本浏览器,你应该将它们升级到支持这些新语言特性的版本。</p>

<pre class="brush: js">"use strict";
class DocArchiver {}

// SyntaxError: class is a reserved identifier
//(只会在旧版本浏览器中抛出,例如 Firefox 44 或更老的版本)
</pre>

<h2 id="相关内容">相关内容</h2>

<ul>
 <li><a href="http://wiki.c2.com/?GoodVariableNames">Good variable names</a></li>
</ul>