简体   繁体   English

为什么带有新函数的setTimeout会忽略等待间隔?

[英]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. 前版本等待500毫秒,然后发出警报。 The latter alerts immediately. 后者立即发出警报。

Why does adding new in front of the function cause this behavior? 为什么在函数前面添加new会导致这种行为?

使用new创建一个使用匿名函数作为其构造函数的新对象,因此您的函数会立即运行并发出警报。

后者实例化一个Object并立即调用其构造函数。

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. 如您所见,第二行使用temp1作为构造函数调用您的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM