Javascript 定时器调用传递参数的方法_javascript技巧

WBOY
Release: 2016-05-16 18:41:56
Original
897 people have browsed it

无论是window.setTimeout 还是window.setInterval,在使用函数名作为调用句柄时都不能带参数,而在许多场合必需要带参数,这就需要想方法解决.
例如对于函数hello(_name),它用于针对用户名显示欢迎信息:

复制代码代码如下:

var userName="Tony";
//根据用户名显示欢迎信息
function hello(_name){
alert("hello,"+_name);
}

这时,如果企图使用以下语句来使hello函数延迟3 秒执行是不可行的:
window.setTimeout(hello(userName),3000);
这将使hello函数立即执行,并将返回值作为调用句柄传递给setTimeout 函数,其结果并不是程序需要的.而使用字符串形式可以达到想要的结果:
window.setTimeout("hello(userName)",3000);
这里的字符串是一段JavaScript 代码,其中的userName 表示的是变量.但这种写法不够直观,而且有些场合必须使用函数名,下面用一个小技巧来实现带参数函数的调用:
复制代码代码如下:



这里定义了一个函数_hello,用于接收一个参数,并返回一个不带参数的函数,在这个函数内部使用了外部函数的参数,从而对其调用,不需要使用参数.在window.setTimeout函数中,使用_hello(userName)来返回一个不带参数的函数句柄,从而实现了参数传递的功能.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!