简体   繁体   English

javascript回调函数的参数

[英]arguments to javascript callback function

var data = [{offset: 2000, str:'foo'}, {offset: 4000, str:'bar'}];

for (var i=0; i<data.length; i++) {
    var x = data[i];
    setTimeout(function(){printStuff(x.str)}, x.offset);
}

function printStuff(str) {
    console.log(str);
}

I was expecting to get printStuff('foo') at 2000 ms offset and printStuff('bar') at 4000 ms offset but instead it prints 'bar' both times. 我原本希望在2000毫秒偏移量时获得printStuff('foo')而在4000毫秒偏移量时获得printStuff('bar') ,但它两次都打印'bar'。 I've no idea what's going on, help please. 我不知道发生了什么事,请帮忙。

Do this : 做这个 :

for (var i = 0; i < data.length; i++) {
    (function (x) {
        setTimeout(function () {
            printStuff(x.str)
        }, x.offset);
    })(data[i]);
}

Your problem is that x has changed in the closure when the function is called. 您的问题是在调用函数时x在闭包中已更改。

You can use functional iteration that gives a closure for free: 您可以使用免费提供闭包的函数迭代:

data.forEach( function( x ) {
      setTimeout( printStuff.bind(null, x.str), x.offset );
});

Shims for all in case oldIE support is required: 如果需要oldIE支持,则适用于所有垫片:

forEach 的forEach

bind 捆绑

setTimeout不会阻止代码继续执行,因此循环完成,并且在执行setTimeout回调时,“ x”的最新值是data数组中的第二个对象。

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

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