2011-03-06 66 views
5

我刚刚问了一下名字调用函数,现在我要处理return语句后SetTimeout获取返回值之后的setTimeout

function ECall(funcName, arg) 
{ 
    command += "("; 
    for (var i=1; i<arguments.length; i++) 
    { 
     command += "'" + arguments[i] + "'"; 
     if (i != arguments.length-1) command += ','; 
    } 
    command += ")"; 

    //var funcPtr = eval(funcName); 
    //return funcPtr(arg); // This works, but I need SetTimeout 

    setTimeout('window[\'' + funcName + '\']' + command, 1000); 
} 

setTimeout的伟大工程,但我必须节省调用函数的返回值。当我写:setTimeout('alert(window[\'' + funcName + '\']' + command + ')', 1000); 它提醒函数的返回值。我如何存储它?

回答

5

你不需要使用任何此字符串操作。只需传递函数参考window.setTimeout()。将函数的返回值,只需将其分配给你写的,这是不可能的setTimeout后得到的返回值,权传递给window.setTimeout()

var savedValue; 

function ECall(funcName) 
{ 
    var args = Array.prototype.slice.call(arguments, 1); 
    var func = window[funcName]; 

    window.setTimeout(function() { 
     savedValue = func.apply(this, args); 
    }, 1000); 
} 
2

如果你想从ECall返回一个值,它将不起作用。

setTimeout是异步的,这意味着ECall将返回被调用setTimeout代码之前。

或者,如果您希望alert()成为setTimeout的一部分,则可以传递匿名函数。另外,最好不要将字符串传递给setTimeout

我应该这样做,而不是:

function ECall(funcName, arg) 
{ 
     // Get an Array of the arguments, except for the first one. 
    var args = Array.prototype.slice.call(arguments, 1); 

     // Pass an anonymous function that calls the global "funcName" function 
     // inside the alert(). 
     // It uses .apply() to pass the arguments we sliced. 
    setTimeout(function() { 
     alert(window[ funcName ].apply(window, args)); 
    }, 1000); 
} 
+1

功能的变量?有没有办法做到这一点? – Ockonal 2011-03-06 15:01:15

+0

@Ockonal:我在答案中使用了一个警告,但是@Tim Down在他的回答中显示了相同的概念(http://stackoverflow.com/questions/5211103/get-return-value-after-settimeout/5211190# 5211190),但将结果存储在预先定义的变量中(这是您似乎想要的)。该值直到'setTimeout'运行才会可用。 – user113716 2011-03-06 15:03:16