39 lines
2.1 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

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: reference to undefined property "x" (Firefox)
</code></pre>
<h2 id="错误类型">错误类型</h2>
<p>仅在 <a href="Reference/Strict_mode">strict mode</a> 下出现 <a href="Reference/Global_Objects/ReferenceError" title="ReferenceError引用错误 对象代表当一个不存在的变量被引用时发生的错误。"><code>ReferenceError</code></a> 警告。</p>
<h2 id="哪里出错了">哪里出错了?</h2>
<p>脚本尝试去访问一个不存在的对象属性。<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessors</a> 页面描述了两种访问属性的方法。</p>
<p>引用未定义属性的错误仅出现在 <a href="Reference/Strict_mode">strict mode </a>代码中。在非严格代码中,对不存在的属性的访问将被忽略。</p>
<h2 id="示例">示例</h2>
<h3 id="无效的">无效的</h3>
<p>本例中,<code>bar</code> 属性是未定义的,隐藏 <code>ReferenceError</code> 会出现。</p>
<pre><code class="language-js example-bad">"use strict";
var foo = {};
foo.bar; // ReferenceError: reference to undefined property "bar"
</code></pre>
<h3 id="无效的_2">无效的</h3>
<p>为了避免错误,您需要向对象添加 <code>bar</code> 的定义或在尝试访问 <code>bar</code> 属性之前检查 <code>bar</code> 属性的存在;一种检查的方式是使用 <a href="Reference/Global_Objects/Object/hasOwnProperty" title="hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性"><code>Object.prototype.hasOwnProperty()</code></a> 方法。如下所示:</p>
<pre><code class="language-js example-good">"use strict";
var foo = {};
// Define the bar property
foo.bar = "moon";
console.log(foo.bar); // "moon"
// Test to be sure bar exists before accessing it
if (foo.hasOwnProperty("bar") {
console.log(foo.bar);
}</code></pre>
<h2 id="相关">相关</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li>
</ul>
</article>