Mankament Gra Mankament Gra - 1 year ago 86
Javascript Question

How can i get window property from element

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


var arr = []

for(var i in window)
console.log("a" in window)// true
console.log(arr)// dont have property a why?!


But when i run console.log(arr) i dont have a in the arrey, why?

Answer Source

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(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.