I would like to know what the difference is between
window.setTimeout(myFancyFunciton, 1000);
and
setTimeout(myFancyFunciton, 1000);
Both seem to do the exact same thing. When should you use one or the other?
JavaScript runs in an environment that is defined by a global object. Methods of the global object can be called without explicitly refering to the object (i.e. without the obj.function()
notation).
When you run JavaScript inside the browser, the global object is provided by the Document Object Model (DOM). The global object of the DOM has a method setTimeout()
. That's why you can call setTimeout()
.
The DOM specifies that the global object has a property named window
, which is a reference back to the global object. That's why you can call window.setTimeout()
and (by transitivity) window.window.setTimeout()
, window.window.window.setTimeout()
, and (you guessed it) window.window.window.window.window.window.window.window.window.setTimeout()
. It's all the same method of the same object.