开发者

Why does setTimeout with new function ignore wait interval?

开发者 https://www.devze.com 2023-04-05 10:05 出处:网络
When trying to do this: setTimeout(function(){alert(\"Boo\");}, 500); I accidentally wrote this: setTimeout(new function(){alert(\"Boo\");}, 500);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号