40 lines
2.8 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">ReferenceError: assignment to undeclared variable "x" (Firefox)
ReferenceError: "x" is not defined (Chrome)
ReferenceError: Variable undefined in strict mode (Edge)
</code></pre>
<h2 id="错误类型">错误类型</h2>
<p>  仅在<a href="Reference/Strict_mode">严格模式</a>中出现 <a href="Reference/Global_Objects/ReferenceError" title="ReferenceError引用错误 对象代表当一个不存在的变量被引用时发生的错误。"><code>ReferenceError</code></a> 警告。</p>
<h2 id="发生了什么">发生了什么?</h2>
<p>在代码里赋值了一个未声明的变量。换句话说,有处没有带着<code><a href="Reference/Statements/var"> var</a></code> 关键字的赋值。<span id="result_box" lang="zh-CN"><span>事实上已声明的和未声明的变量之间有一些差异,这可能会导致意想不到的结果,这就是为什么 JavaScript 在严格模式打印出这种错误。</span></span></p>
<p><span class="short_text" id="result_box" lang="zh-CN"><span>关于已声明和未声明的变量,其有三个注意事项:</span></span></p>
<ul>
<li><span class="short_text" id="result_box" lang="zh-CN"><span>已声明的变量被约束在其执行上下文中</span></span><span class="short_text" lang="zh-CN"><span></span><span>未声明的变量总是全局的。</span></span></li>
<li><span class="short_text" id="result_box" lang="zh-CN"><span>已声明的变量在执行任何代码之前就创建了</span></span><span class="short_text" lang="zh-CN"><span>。未声明的变量则不存在,直到执行相关的代码。</span></span></li>
<li><span class="short_text" id="result_box" lang="zh-CN"><span>已声明的变量是其执行上下文(函数或全局)的不可配置属性。</span><span>而未声明的变量是可配置的(例如可以删除)。</span></span></li>
</ul>
<p>更多信息及例子,请参考 <code><a href="Reference/Statements/var">var</a></code> 页面。</p>
<p>关于未声明变量的赋值的错误仅在<a href="Reference/Strict_mode">严格模式</a>里出现。在非严格模式中,这些将被忽略。</p>
<h2 id="示例">示例</h2>
<h3 id="无效的">无效的</h3>
<p>在本例中,"bar" 是未声明的变量。</p>
<pre><code class="language-js example-bad">function foo() {
"use strict";
bar = true;
}
foo(); // ReferenceError: assignment to undeclared variable bar
</code></pre>
<h3 id="有效的">有效的</h3>
<p>为了使 "bar" 是一个已声明变量,你需要在其前面加一个 var 关键字。</p>
<pre><code class="language-js example-good">function foo() {
"use strict";
var bar = true;
}
foo();</code></pre>
<h2 id="相关">相关</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li>
</ul>
</article>