uTools-Manuals/docs/javascript/Reference/Errors/Reserved_identifier.html

50 lines
2.6 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<article id="wikiArticle">
<div></div>
<h2 id="消息提示">消息提示</h2>
<pre><code class="language-javascript">SyntaxError: "x" is a reserved identifier (Firefox)
SyntaxError: Unexpected reserved word (Chrome)</code></pre>
<h2 id="错误类型">错误类型</h2>
<p><a href="Reference/Global_Objects/SyntaxError" title="SyntaxError 对象代表尝试解析语法上不合法的代码的错误。"><code>SyntaxError</code></a></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><a href="Reference/Statements/let" title="let允许你声明一个作用域被限制在块级中的变量、语句或者表达式。与var关键字不同的是var声明的变量只能是全局或者整个函数块的。"><code>let</code></a></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><code class="language-js example-bad">var enum = { RED: 0, GREEN: 1, BLUE: 2 };
// SyntaxError: enum is a reserved identifier
</code></pre>
<p>在严格模式下,会有更多的保留字。</p>
<pre><code class="language-js example-bad">"use strict";
var package = ["potatoes", "rice", "fries"];
// SyntaxError: package is a reserved identifier
</code></pre>
<p>你需要对上述变量重新命名。</p>
<pre><code class="language-js example-good">var colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
var list = ["potatoes", "rice", "fries"];</code></pre>
<h3 id="升级旧版本浏览器">升级旧版本浏览器</h3>
<p>假如你还在使用尚未支持 let 或 class 等特性的旧版本浏览器,你应该将它们升级到支持这些新语言特性的版本。</p>
<pre><code class="language-javascript">"use strict";
class DocArchiver {}
// SyntaxError: class is a reserved identifier
//(只会在旧版本浏览器中抛出,例如 Firefox 44 或更老的版本)
</code></pre>
<h2 id="相关内容">相关内容</h2>
<ul>
<li><a class="external" href="http://wiki.c2.com/?GoodVariableNames" rel="noopener">Good variable names</a></li>
</ul>
</article>