gpt4 book ai didi

javascript - 当作为参数传递给 setTimeout 回调函数时,全局变量被记录为未定义

转载 作者:数据小太阳 更新时间:2023-10-29 04:00:13 26 4
gpt4 key购买 nike

我有一些 JS 代码如下:

var x = self.someAJAXResponseJSON; // x has some object value here.

setTimeout(function(x){
console.log("In setTimeout:", x); // But x is undefined here
}, 1000);

所以我想将x传递给setTimeout回调函数。但是我在 setTimeout 中得到的 x 是未定义的。

我做错了什么?

知道如何使用 Dojo.js 解决类似问题吗?

setTimeout(dojo.hitch(this, function(){
this.executeSomeFunction(x); // What should this be?
console.log("In setTimeout:", x); // But x is undefined here
}), 1000);

最佳答案

或者,您可以在不创建闭包的情况下执行此操作。

function myFunction(str1, str2) {
alert(str1); //hello
alert(str2); //world
}

window.setTimeout(myFunction, 10, 'hello', 'world');

但请注意它不适用于 IE < 10 according to MDN .

关于javascript - 当作为参数传递给 setTimeout 回调函数时,全局变量被记录为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32326721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com