26

我有一些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);

所以我想传递xsetTimeout回调函数。但我xsetTimeout.

我究竟做错了什么?

知道如何使用 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);
4

6 回答 6

31

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

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

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

IE < 10 但请注意,根据 MDN,它不起作用。

于 2015-09-01T08:28:11.863 回答
15

调用回调时setTimeout,它不传递任何参数(默认情况下);也就是说,x调用回调时参数未定义。

如果删除参数xx则函数体中将不会引用未定义的参数,而是引用您在调用之外定义的变量setTimeout()

var x = "hello";
setTimeout(function () { //note: no 'x' parameter
    console.log("setTimeout ... : " + x);
}, 1000);

或者,如果它必须是参数,您可以将其作为参数传递给setTimeout(不过,请帮自己一个忙,并以不同的方式命名):

var x = "hello";
setTimeout(function (y) {
    console.log("setTimeout ... : " + y);
}, 1000, x);
于 2015-09-01T08:18:58.013 回答
6

我自己遇到了这个并查看了节点文档,要传递给函数的参数作为 setTimeout 调用的第三个(或更多)参数进来,所以......

myfunc = function(x){console.log(x)};
x = "test";
setTimeout(myfunc,100,x);

为我工作。

于 2018-05-07T20:12:05.457 回答
2

这是因为函数在没有传递任何参数的情况下被调用:所以x是未定义的。

如果您愿意为x使用不同的参数调用它,则应该将其包装在一个闭包中:

var x = self.someAJAXResponseJSON; // x has some object value here
setTimeout((function(y){
    return(function() {
        console.log("setTimeout ... : " + y);
    })
})(x), 1000);
于 2015-09-01T08:20:29.120 回答
2

在您的代码中,console.log(x)x的是回调函数的参数。

只需从函数签名中省略它,就可以了:

setTimeout(function(){
  console.log("setTimeout ... : " + x); // now x is the global x
}, 1000);
于 2015-09-01T08:18:27.557 回答
0

setTimeout 方法旨在将函数或代码片段作为其第一个参数,但在您的情况下,您使用了一个带有参数 x 的匿名函数,并且在不带任何参数的情况下调用该函数,因此它显示为未定义,因为没有定义接受 x 的具体函数. 你可以做的是你可以先定义你想要调用的函数,然后在 setTimeout 方法中调用它。请参阅以下代码片段:

var x = self.someAJAXResponseJSON;
function mylog(x){
  console.log("setTimeout ... : " + x);
}
setTimeOut(mylog(x),1000);
于 2015-09-01T08:29:09.493 回答