2

Considering the code below. I'm defining a property on an object Weird for a reset button which is in present in the DOM. However, if I check the window - the property is also present? How come this happens?

I'm browsing in Chrome Version 49.0.2623.87 (64-bit).

var Weird = Weird || {};

Weird.start = function(){
  this.reset = document.getElementById("reset");
};

document.addEventListener("DOMContentLoaded", function(){
  Weird.start();

  console.log(Weird.reset) // Works but expected
  console.log(reset); // Works?
  console.log(window.reset); // Works?
  console.log(window.Weird.reset); // Works?
});
Alex Chin
  • 1,642
  • 15
  • 28
  • 1
    Browsers create global symbols (properties of the `window` object) for elements whose "id" attributes are valid identifiers. (Maybe it's for all "id" values; I hate that behavior and never use it so I'm not sure.) – Pointy Mar 22 '16 at 15:37
  • Try changing either the "id" of the element or the name of the method in your `Weird` object and you'll see. – Pointy Mar 22 '16 at 15:40
  • @Pointy That behaviour seems like it conflicts with scope? What if I don't want the `Weird.reset` to be accessible to window? – Alex Chin Mar 22 '16 at 16:50
  • It's not `Weird.reset` that's accessible. If you had no JavaScript at all, there would still be `window.reset` because you gave your element the "id" value "reset". – Pointy Mar 22 '16 at 19:36
  • @Pointy Okay. Yes that makes sense. So Chrome just grabs every element on the page with an id and assigns it to a variable of the same name. – Alex Chin Mar 23 '16 at 14:18
  • Yes; at this point all browsers do. Firefox did not for quite some time, but now it does. The behavior was originally an Internet Explorer quirk. – Pointy Mar 23 '16 at 14:23
  • Here is a similar question http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – Alex Chin Mar 23 '16 at 14:51

0 Answers0