Why does setTimeout with new function ignore wait interval?
When trying to do this:
setTimeout(function(){alert("Boo");}, 500);
I accidentally wrote this:
setTimeout(new function(){alert("Boo");}, 500);
The former version waits 500 millis, then alerts. The latter alerts immediately.
Why does adding new
in front开发者_StackOverflow中文版 of the function cause this behavior?
Using new
creates a new object using the anonymous function as its constructor, so your function runs and alerts immediately.
The latter one instantiates an Object
and calls its constructor immediately.
new function(){alert("Boo");}
is an equivalent of
var temp1 = function(){alert("Boo");};
var temp2 = new temp1();
second line as you see invokes your function using temp1 as a constructor.
精彩评论