Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

ReferenceError: reference to undefined property "x"

我們的志工尚未將此文章翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!

Message

ReferenceError: reference to undefined property "x" (Firefox)

Error type

ReferenceError warning in strict mode only.

What went wrong?

The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the property accessors reference page to learn more about them.

Errors about references to undefined properties occur in strict mode code only. In non-strict code, accesses to properties that don't exist are silently ignored.

Examples

Invalid cases

In this case, the property bar is an undefined property, so a ReferenceError will occur.

"use strict"; 

var foo = {};
foo.bar; // ReferenceError: reference to undefined property "bar"

Valid cases

To avoid the error, you need to either add a definition for bar to the object or check for the existence of the bar property before trying to access it; one way to do that is to use the Object.prototype.hasOwnProperty() method), like this:

"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);
}

See also

文件標籤與貢獻者

 此頁面的貢獻者: Sheppy, fscholz
 最近更新: Sheppy,