Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - Why does accessing a non-existent object property result in `undefined` instead of throwing a `ReferenceError`?

When I try to use an undeclared variable I get ReferenceError:

console.log(a); // Uncaught ReferenceError: a is not defined

I could use a variable first and define it later and it won’t be a problem due to hoisting.

console.log(a); // undefined

var a;

But when I declare an object why would the execution context let me use any property of it?

var obj = {};

console.log(obj.a); // undefined
console.log(obj.why); // undefined

Why are these allowed even though a and why are never declared anywhere?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because object properties are not variables. The rules are different. Accessing an object property that doesn't exist gives you undefined, not an error. It's just the way the language is designed.

One possible explanation for the difference, other than just that "that's how Eich designed it," is that you don't declare object properties. You just use them. But variables must be declared (other than The Horror of Implicit Globals, and we don't have that now we have strict mode).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...