gpt4 book ai didi

javascript - 下划线 _.delay 实现

转载 作者:行者123 更新时间:2023-11-29 21:46:15 25 4
gpt4 key购买 nike

为什么延迟的第一个实现不起作用?

另外,第三个如何在不使用 Array.prototype.slice.call 的情况下工作?

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

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

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

最佳答案

Why does the first implementation of delay not work?

因为 setTimeout(<strong>func(args)</strong>, wait);调用 func化。现在。在将调用结果传递给 setTimeout 之前.但这确实需要回调函数稍后调用!

Also how does the 3rd one work without using Array.prototype.slice.call?

因为 apply 也接受 arguments objects直接,不仅仅是数组。但是,我猜你真的想知道为什么

_.delay = function(func, wait, ...args) {
return setTimeout(func, wait, ...args); // using rest arguments
};

有效吗?因为那就是 setTimeout 处理多余的参数1 - 将它们传递给延迟的 func打电话。

1:在大多数实现中。旧的 IE 没有。

关于javascript - 下划线 _.delay 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com