-->

Is there a need to prepend setTimeout and setInter

2019-07-15 12:25发布

问题:

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.

回答1:

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.



回答2:

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.