blob: 9cda2d050156b19e0760f61534236fe7e598cfc5 (
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
|
---
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>
|