0
<body>
<h1 id="a">Site 3</h1>

<script>

var arr = []

for(var i in window)
{
    arr.push(i) 
}
console.log("a" in window)// true
console.log(arr)// dont have property a why?!
</script>

</body>

But when I run console.log(arr) I don't have a in the array, why?

1 Answers1

2

The things accessible on window are not necessarily "own" properties of window and (this is the significant bit) are not necessary enumerable. for-in only visits enumerable properties (both "own" and inherited).

On Chrome, for instance, the automatic a global is a property of the prototype of the prototype of window, and it's marked as non-enumerable:

var o = window;
var where = "window"
while (o && !Object.getOwnPropertyDescriptor(o, "a")) {
  where = "prototype of " + where;
  o = Object.getPrototypeOf(o);
}

console.log(where);
console.log(Object.getOwnPropertyDescriptor(o, "a"));
<div id="a"></div>

Looks like it's in the same place on Firefox.

The exact semantics of how named access is achieved isn't dictated, so long as in works and window.a works.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • ok, so why "a" is in prototype of prototype window rather than window? – Mankament Gra Oct 30 '16 at 20:38
  • @MankamentGra: According to the above it's on the *prototype* of the prototype of `window`. I don't know, at that point we're into implementation details, but `window` is **very** complicated, taking things from lots of different places, incorporating the [`WindowProxy` object](https://www.w3.org/TR/html5/browsers.html#the-windowproxy-object), etc. I'm not surprised to find three layers to it. – T.J. Crowder Oct 31 '16 at 07:42