我如何传递参数到使用setTimeout调用的函数? [英] How can I pass an argument to a function called using setTimeout?

查看:431
本文介绍了我如何传递参数到使用setTimeout调用的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个参数到使用 setTimeout 调用的函数。我找到了这三个选项:

  A = 1; 
//方法1:关闭事物
setTimeout(function(){whatsA(A);},100);
//方法2:第三个参数(与[A]相同的结果)
setTimeout(whatsA,100,A);
//方法3:eval
setTimeout('whatsA('+ A +')',100);
A = 2;
function whatsA(X){console.log(X); }

这将显示 2 undefined 1



方法1 :很明显,我不喜欢在传递参数后更改参数(当然在简单整数的情况下)。



方法3 :这似乎是唯一的选择。



有更好的方法吗?

div =h2_lin>解决方案

我可以想到的最好的解决方案是使用 bind()

  A = 1; 
setTimeout(whatsA.bind(this,A),100);

因为 bind()实际上是一个函数调用,它读取当前的 A 值,并返回一个以该值作为参数的函数。如果你觉得很难理解,试试这个:

  var newFun = whatsA.bind(this,42) 
newFun()

请注意 this 这里是一个谎言 - 你可以安全地通过窗口






第一种方法也是可以接受的,只是需要略微改进:

  A = 1; 
var tmpA = A;
setTimeout(function(){whatsA(tmpA);},100);

你所观察到的实际上是一个功能,而不是一个错误。你传递一个闭包到 setTimeout()引用局部变量。 JavaScript是足够聪明的,以延迟对该变量的访问,直到函数被实际调用的那一刻。






第二种方法已弃用 won






第三种方法很可怕,避免将字符串传递给 setTimeout(),总有一个更好的解决方案。


I want to pass an argument to a function called using setTimeout. I have found these three options:

A = 1;
// Method 1: closure things
setTimeout(function() { whatsA(A); }, 100);
// Method 2: third argument (same result with [A])
setTimeout(whatsA, 100, A);
// Method 3: eval
setTimeout('whatsA(' + A + ')', 100);
A = 2;
function whatsA(X) { console.log(X); }

This shows 2, undefined, and 1 in Internet Explorer 9.

Method 1: Clearly, I would not like the argument to be changed after passing it (certainly in the case of simple integers).

Method 2: This would be perfect if only Internet Explorer supported it.

Method 3: This seems to be the only choice. But it seems rather less pretty than the others, passing something to be evaluated rather than a function.

Is there a better way?

解决方案

The best solution I can think of is using bind():

A = 1;
setTimeout(whatsA.bind(this, A), 100);

Because bind() is actually a function invocation, it reads the current A value and returns a function with that value bound as an argument. If you find it hard to understand, try this:

var newFun = whatsA.bind(this, 42);
newFun()

Note that this is kind of a lie here - you can safely pass window as well.


The first method is also acceptable, it just needs to be slightly improved:

A = 1;
var tmpA = A;
setTimeout(function() { whatsA(tmpA); }, 100);

What you are observing is actually a feature, not a bug. You are passing a closure to setTimeout() referencing local variable. JavaScript is clever enough to delay access to that variable up to the moment when the function is actually called. And since you have modified the variable, you see the most recent version.


The second method is deprecated won't work in any browser.


Third method is terrible, avoid passing string to setTimeout(), there is always a better solution.

这篇关于我如何传递参数到使用setTimeout调用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆