Reputation: 230156
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 of the function cause this behavior?
Upvotes: 4
Views: 517
Reputation: 27470
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.
Upvotes: 0
Reputation: 38264
Using new
creates a new object using the anonymous function as its constructor, so your function runs and alerts immediately.
Upvotes: 5
Reputation: 490403
The latter one instantiates an Object
and calls its constructor immediately.
Upvotes: 2