开发者

What's the difference between undefined and window.undefined in JavaScript?

开发者 https://www.devze.com 2022-12-25 15:42 出处:网络
If a is undefined, this works: if(window.a) {} while this throws an error: if(a) Can 开发者_StackOverflow中文版someone explain why?window.a is a property of window and it\'s undefined. a is a va

If a is undefined, this works:

if(window.a) {}

while this throws an error:

if(a)

Can 开发者_StackOverflow中文版someone explain why?


window.a is a property of window and it's undefined. a is a variable, and it's undeclared.

To use a variable, you should first declare it using the var statement. Since you didn't declare a, the interpreter raises an error. Object properties are not needed to be explicitly declared in order to use them. Crockford writes in The Good Parts:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消