This question ( Element accessible with ID ) points out that if an element has an id then you can access it by variable name based on that id. It intrigued me, as I had seen this variable available when developing using Visual Studio 2010. I did some testing out of curiosity and it turns out that document.getElementById()
was still faster than using the variable name. So, I began trying to look through the window, figuring it must be in window["idName"]
, in debug, and with console.log(window)
and could not find where the variable was actually stored.
When an element is defined in html with <div id="foo">
it is available in javascript with the variable foo
(I am not suggesting to use this, it is bad practice). Where is that variable stored?
This is non-standard behavior. Where (and if) it is stored is up to the implementation.
Using Firefox 15
on Linux, I had to go 2 prototype objects deep to find the actual object. I ran this code on this StackOverflow page, and got a true
result.
Object.getPrototypeOf(Object.getPrototypeOf(window)).hasOwnProperty("hlogo");
In Chrome on Linux, it was one level deep.
Object.getPrototypeOf(window).hasOwnProperty("hlogo");
I was actually surprised to see it in Firefox, but since Chrome followed the Microsoft pattern, I guess Firefox must have felt the need to follow suit.
If you don't know how deep a prototype chain is, you can run a loop, and add the different objects to an Array, or just work with the objects in the loop.
var protos = [],
obj = window;
while (Object.getPrototypeOf(obj) !== null) {
obj = Object.getPrototypeOf(obj);
protos.push(obj);
}
alert("The object had " + protos.length + " prototype objects");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With