Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

why referencing non-existent property of an object in javascript doesn't return a reference error?

If I try to reference a non-existent variable, I get ReferenceError in JavaScript. Why referencing a non-existent object property returns 'undefined'? Here is some code, provided I'm writing it in a browser:

alert(a);
ReferenceError: a is not defined //error is thrown
alert({}.a)
undefined //no error
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

That's just how the language works. Its object-based approach is very flexible, and you can dynamically add, update, and remove properties from objects at runtime. Accessing one that is currently not existing should yield undefined instead of raising an exception. This, for example, allows checking for existence and type in a single expression:

if (prop in obj && typeof obj[prop] == "function") obj[prop]();
// can be written shorter:
if (typeof obj[prop] == "function") obj[prop]();

You can get the value without using it. Using undefined then will throw in most circumstances.

In contrast, variables are declared statically in their scope. Accessing an undeclared variable is always an error, which legitimates throwing ReferenceErrors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...