如果您的dothis 函数不需要返回值,您可以让它自己返回。
这将允许您同时调用和传递它。如果返回值被忽略,将是无害的。
function dothis() {
// your code
return dothis;
}
var i = setInterval(dothis(), 20000);
否则,您可以扩展 Function.prototype 为您的所有函数提供调用和返回功能:
演示: http://jsfiddle.net/ZXeUz/
Function.prototype.invoke_assign = function() {
var func = this,
args = arguments;
func.call.apply( func, arguments );
return function() { func.call.apply( func, args ); };
};
setInterval( dothis.invoke_assign( 'thisArg', 1, 2, 3 ), 20000 );
// thisArg 1 2 3
// thisArg 1 2 3
// thisArg 1 2 3
// ...
这实际上增强了一些东西。它允许您传递一组参数。第一个参数将设置您正在调用的函数的 this 值,其余参数将作为常规参数传递。
因为返回的函数被包装在另一个函数中,所以在初始调用和间隔调用之间会有相同的行为。