当作为参数传递给 setTimeout 回调函数时,全局变量被记录为未定义 [英] Global variable is logged as undefined when passed as parameter to setTimeout callback function
本文介绍了当作为参数传递给 setTimeout 回调函数时,全局变量被记录为未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些JS代码如下:
var x = self.someAJAXResponseJSON;//x 在这里有一些对象值.设置超时(函数(x){console.log("In setTimeout:", x);//但是这里 x 是未定义的}, 1000);
所以我想将 x
传递给 setTimeout
回调函数.但是我在 setTimeout
中将 x
设为未定义.
我做错了什么?
知道如何使用 Dojo.js 解决类似问题吗?
setTimeout(dojo.hitch(this, function(){this.executeSomeFunction(x);//这应该是什么?console.log("In setTimeout:", x);//但是这里 x 是未定义的}), 1000);
解决方案
或者,您可以在不创建闭包的情况下完成.
function myFunction(str1, str2) {警报(str1);//你好警报(str2);//世界}window.setTimeout(myFunction, 10, 'hello', 'world');
但请注意它不适用于 IE <10
根据 MDN.>
I have some JS code as below:
var x = self.someAJAXResponseJSON; // x has some object value here.
setTimeout(function(x){
console.log("In setTimeout:", x); // But x is undefined here
}, 1000);
So I want to pass x
to the setTimeout
callback function. But I am getting x
as undefined inside the setTimeout
.
What am I doing wrong?
Any idea how to fix a similar issue using 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);
解决方案
Alternatively you can do it without creating a closure.
function myFunction(str1, str2) {
alert(str1); //hello
alert(str2); //world
}
window.setTimeout(myFunction, 10, 'hello', 'world');
But note it doesn't work on IE < 10
according to MDN.
这篇关于当作为参数传递给 setTimeout 回调函数时,全局变量被记录为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文