window的属性和全局变量的区别

Difference between window's properties and global variable

我尝试在浏览器中 运行 下面的代码。我以为 属性 window.a 和全局 a 是内存中的同一个单元格。有人可以给我 link 一篇解释这种行为的文章吗?

// undefined
// if (window.a) {}

// Uncaught ReferenceError: a is not defined
// if (a) {} 

它们是相同的:

a = 1;
a === window.a // true

编辑:抱歉,有点太快了...我没有回答任何问题。这篇文章很好地解释了差异: https://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/

"A Reference is considered unresolvable if its base value is undefined"

window.a // base value is window, reference object is a
a // base value is a

window 是一个对象,并且尝试访问未在对象上设置的键总是 returns undefined,即使变量 a 没有已设置。

var a = {}
a.b
>>> undefined

不同之处在于 a 执行变量查找(失败,因为您没有定义它),而 window.a 在 [=11] 上执行 属性 查找=] 对象,其中 returns undefined.