_.delay函数缺少什么?

时间:2015-12-09 23:18:25

标签: javascript function underscore.js

这是一个我知道很简单的问题,但我被卡住了。如果你能帮我弄清楚我的代码中缺少什么,我将不胜感激。我需要传递两个测试 1)应该在特定的等待时间后执行函数, 2)应该已成功传递函数参数。下面的说明和我的代码一样。我的问题是代码通过了第一次测试,但没有通过第二次测试。

说明:

  

“将函数延迟给定的毫秒数,然后使用提供的参数调用它。原始函数的参数在wait参数之后传递。例如_.delay(someFunction,500,'a', 'b')将在500ms“

之后调用someFunction('a','b')

我的代码:

_.delay = function(func, wait) {
    return setTimeout(function(){
        return func.call(this, arguments);
    }, wait);
};

1 个答案:

答案 0 :(得分:2)

正如你所说:

  

原始函数的参数在wait参数之后传递。例如_.delay(someFunction,500,'a','b')将在500ms之后调用someFunction('a','b')“

您正在做的不是someFunction('a','b')而是someFunction(someFunction, wait,'a','b')

所以你需要做的是采取除前两个参数之外的所有参数,这可以通过var args = Array.prototype.slice.call(arguments,2)

来完成

因为您要传递数组,所以需要使用apply而不是callRelated question about the difference between call and apply

所以你最终的代码是这样的:

_.delay = function(func, wait) {
    var args = Array.prototype.slice.call(arguments,2);
    return setTimeout(function(){
        return func.apply(this, args);
    }, wait);
};

您可以随时查看the annotated source of underscorejs

相关问题