diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
| commit | 33058f2b292b3a581333bdfb21b8f671898c5060 (patch) | |
| tree | 51c3e392513ec574331b2d3f85c394445ea803c6 /files/zh-cn/web/javascript/reference/errors/undefined_prop | |
| parent | 8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff) | |
| download | translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2 translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip | |
initial commit
Diffstat (limited to 'files/zh-cn/web/javascript/reference/errors/undefined_prop')
| -rw-r--r-- | files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html b/files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html new file mode 100644 index 0000000000..9cda2d0501 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html @@ -0,0 +1,64 @@ +--- +title: 'ReferenceError: reference to undefined property "x"' +slug: Web/JavaScript/Reference/Errors/Undefined_prop +tags: + - Errors + - JavaScript + - ReferenceError + - Strict Mode + - 严格模式 +translation_of: Web/JavaScript/Reference/Errors/Undefined_prop +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="信息">信息</h2> + +<pre class="syntaxbox">ReferenceError: reference to undefined property "x" (Firefox) +</pre> + +<h2 id="错误类型">错误类型</h2> + +<p>仅在 <a href="/zh-CN/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> 下出现 {{jsxref("ReferenceError")}} 警告。</p> + +<h2 id="哪里出错了">哪里出错了?</h2> + +<p>脚本尝试去访问一个不存在的对象属性。<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessors</a> 页面描述了两种访问属性的方法。</p> + +<p>引用未定义属性的错误仅出现在 <a href="/zh-CN/docs/Web/JavaScript/Reference/Strict_mode">strict mode </a>代码中。在非严格代码中,对不存在的属性的访问将被忽略。</p> + +<h2 id="示例">示例</h2> + +<h3 id="无效的">无效的</h3> + +<p>本例中,<code>bar</code> 属性是未定义的,隐藏 <code>ReferenceError</code> 会出现。</p> + +<pre class="brush: js example-bad">"use strict"; + +var foo = {}; +foo.bar; // ReferenceError: reference to undefined property "bar" +</pre> + +<h3 id="无效的_2">无效的</h3> + +<p>为了避免错误,您需要向对象添加 <code>bar</code> 的定义或在尝试访问 <code>bar</code> 属性之前检查 <code>bar</code> 属性的存在;一种检查的方式是使用 {{jsxref("Object.prototype.hasOwnProperty()")}} 方法。如下所示:</p> + +<pre class="brush: 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); +}</pre> + +<h2 id="相关">相关</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> +</ul> |
