带有和不带引号和括号的setTimeout之间的区别 [英] Difference between setTimeout with and without quotes and parentheses
问题描述
我正在学习JavaScript,最近我学到了关于JavaScript计时事件的知识。当我在 W3Schools setTimeout 时>,我注意到一个奇怪的人物,我之前没有遇到过。他们使用双引号然后调用函数。
I am learning JavaScript and I have learned recently about JavaScript timing events. When I learned about setTimeout
at W3Schools, I noticed a strange figure which I didn’t run into before. They are using double quotes and then call the function.
示例:
setTimeout("alertMsg()", 3000);
我知道JavaScript中的双引号和单引号表示字符串。
I know that double and single quotes in JavaScript means a string.
我也看到我可以这样做:
Also I saw that I can do the same like that:
setTimeout(alertMsg, 3000);
使用它所引用的括号,没有括号将其复制。当我使用引号和括号时,它变得疯狂。
With the parentheses it’s referring, without the parentheses it’s copied. When I am using the quotes and the parentheses it’s getting crazy.
如果有人能向我解释这三种使用方法之间的差异,我会很高兴 setTimeout
:
I will be glad if someone can explain to me the difference between these three ways of using setTimeout
:
括号:
setTimeout("alertMsg()", 3000);
没有引号和括号:
setTimeout(alertMsg, 3000);
第三种只使用报价:
setTimeout("alertMsg", 3000);
注意:<$ c $的更好来源c> setTimeout 引用将是 MDN 。
推荐答案
使用 setInterval
或 setTimeout
您应该将对函数的引用作为 setTimeout
的第一个参数传递给的setInterval
。此引用可以采用以下形式:
Using setInterval
or setTimeout
You should pass a reference to a function as the first argument for setTimeout
or setInterval
. This reference may be in the form of:
-
匿名函数
An anonymous function
setTimeout(function(){/* Look mah! No name! */},2000);
现有功能的名称
A name of an existing function
function foo(){...}
setTimeout(foo, 2000);
指向现有函数的变量
A variable that points to an existing function
var foo = function(){...};
setTimeout(foo, 2000);
请注意我将函数中的变量与函数名称分开设置。变量和函数名称占用相同的命名空间并且可以互相破坏是不明显的。
要调用函数并传递参数,可以在分配给计时器的回调中调用函数:
To call a function and pass parameters, you can call the function inside the callback assigned to the timer:
setTimeout(function(){
foo(arg1, arg2, ...argN);
}, 1000);
还有另一种方法可以将参数传递给处理程序,但它不兼容跨浏览器。
There is another method to pass in arguments into the handler, however it's not cross-browser compatible.
setTimeout(foo, 2000, arg1, arg2, ...argN);
回调上下文
默认情况下,执行时回调的上下文(计数器调用的函数内的 this
的值)是全局对象窗口
。如果您想更改它,请使用 bind
。
Callback context
By default, the context of the callback (the value of this
inside the function called by the timer) when executed is the global object window
. Should you want to change it, use bind
.
setTimeout(function(){
this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);
安全性
虽然有可能,但是你应不将字符串传递给 setTimeout
或 setInterval
。传递字符串使 setTimeout()
或 setInterval()
使用类似于 eval()
执行字符串作为脚本,任意可能有害的脚本执行。
Security
Although it's possible, you should not pass a string to setTimeout
or setInterval
. Passing a string makes setTimeout()
or setInterval()
use a functionality similar to eval()
that executes strings as scripts, making arbitrary and potentially harmful script execution possible.
这篇关于带有和不带引号和括号的setTimeout之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!