Which way is better, setInterval() or window.setInterval()?
Ok so there is a couple things to this question.
First o开发者_运维知识库f all, i'm asking this for setTimeout() and for setInterval()
I have seen a couple different ways to call them and i'm wondering which way is the best for this circumstance..
I'm making a js/canvas game and I'm just looking over my draw interval (where it loops the draw method)
Anyways, here are the different ways I have seen...
Part A:
- Using window. - drawInterval = window.setInterval(draw, 60);
- Not using window. - drawInterval = setInterval(draw, 60);
Part B:
- Not using quotes and brackets around the function name - drawInterval = setInterval(draw, 60);
- Using quotes and brackets around the function name - drawInterval = setInterval("draw()", 60);
So for Part A: should i use window. or not? And what about window.clearInterval() vs clearInterval by itself?
And for Part B: should I use quotes and brackets or not? I was told before that it was a bad idea to use quotes and brackets for this situation.
- Unless you've declared your own locally scoped - setIntervalfunction, there's no difference between- setIntervaland- window.setInterval.
- The second form uses an implied - eval(). This should be avoided when possible because it presents the potential for code injection.
- windowis the global object. Whether or not you use it explicitly is something of a matter of style, but as a Python developer, I think explicit is better.
- If you use quotes, the setInterval() essentially "evals" the statement. That's bad. Don't use the quotes. 
window.setInterval() and setInterval() are exactly the same - the window part is implicit and can be omitted.
both setTimeout and setInterval will eval a string, but best practice is to sent a reference to the function - therefore no quotes.
The calls in part A are the same (unless you redeclare one of those functions somewhere). It comes down to preference- I prefer to leave off window as it's unnecessary.
For part B, option 1 is definitely the better practice. Option 2 is going to eval that string, and eval should almost always be avoided.
As for prefixing it with window., there's not a lick of difference.  You can use either.
Not sure on the window.setInterval vs just setInterval
But, it's better to always pass a function, rather than string to setInterval and setTimeout
Another good reason to use window.setTimeout instead of just setTimeout is that it allows you to give just a single declaration to jshint of which global objects your code depends on:
/*global window */
thus allowing access to all of the window methods without having to specify each of them individually in your jshint directives.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论