2

In the Mozilla documentation, there are some examples written with window. in front of the timer functions and some without:

function delayedAlert() {
  timeoutID = window.setTimeout(slowAlert, 2000);
}...

setTimeout(myArray.myMethod, 1000);...

window.setInterval = function (vCallback, nDelay...

I have been writing my code without window. in front without any problem so far. I want to find out if there is any situation when it would be necessary.

Question Overflow
  • 10,925
  • 18
  • 72
  • 110
  • No, as `window` is the global namespace. – Šime Vidas Nov 21 '13 at 03:01
  • Oh I see you already deleted your other question, either way there's one more way to assign and execute a function inline but it's rather ugly as well: `(o.func = function(){}).call(o);` ([fiddle](http://jsfiddle.net/rhQ2W/)) – Fabrício Matté Nov 21 '13 at 07:30

2 Answers2

2

If ..

  1. There is no other identifier in scope with the given name (x or window), and;
  2. There is no with binding that resolves the given name (x or window), and;
  3. The given name (x) is a property in the global scope (window)

.. then window.x and x are equivalent.

For standards-mandated global properties/functions (which must exist in the global scope of a sane web-browser environment), I do not include window. I also take care not to shadow such names.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • @QuestionOverflow However, do realize that `window.y` and `y` act a good bit differently when there is *no* such binding: an unbound identifier `y` can throw a ReferenceError, while a non-existent property evaluates to `undefined`. – user2864740 Nov 21 '13 at 03:05
  • As in the latter will trigger an error? Yes, I get it. Thanks :) – Question Overflow Nov 21 '13 at 03:08
1

No you do not have to add it, the 'window' part is implicit as the root object is window. However, people continue to add it as it denotes a built-in, rather than a user defined function.

Rob M.
  • 35,491
  • 6
  • 51
  • 50