我正在学习下划线延迟来提高我的JS技能,我正在努力向自己解释每一行以确保我理解。有人可以解释这条线路在做什么吗?
var args = Array.prototype.slice.call(arguments, 2);
它是否采用了arguments数组的前2个值并使其等于var'args'?
另外,
不应该“等待”是一个像3000毫秒的数值吗?想知道为什么要拼写出来?
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
setTimeout(function(){
func.apply(this, args);
}, wait);
};
答案 0 :(得分:1)
var args = Array.prototype.slice.call(arguments, 2);
此行除了传递给_delay
的前2个参数外,都会将这些参数传递给setTimeout
。
wait
已拼写出来,因为它是您传递给_.delay()
的参数:
_.delay(function(){
// Do stuff
}, 1000)`;
此参数也会传递给setTimeout
基本上,_.delay
的实现与setTimeout
完全相同,但缺点是它不会返回可用于{{的超时标识符3}}
答案 1 :(得分:1)
var args = Array.prototype.slice.call(arguments, 2);
从第二个索引开始从数组中提取(返回)所有元素。在浏览器控制台中尝试:
Array.prototype.slice.call([1, 2, 3, 4, 5], 2)
// Output: [3, 4, 5]
关于wait
:因为wait
是传递的参数之一,所以它被拼写出来。 wait
的内容应该是一个整数(以毫秒为单位),因为setTimeout(callback, timeInMilliseconds)
期望作为第二个参数。