我有一个取自web的debounce函数。
function debounce(f, ms) {
let timer = null;
return function(...args) {
const onComplete = () => {
f.apply(this, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
}
}我们到底为什么需要这一行f.aply(this, args),如果我们把这一行改为f(args),结果就会一样。
发布于 2019-08-02 22:22:50
如果在不使用this的情况下调用去抖动函数
let deb = debounce(...);
deb()这没什么区别。
如果使用this (通过bind/call/apply)调用它,则需要apply行才能将this正确地传递给源函数:
"use strict";
function debounce(f, ms) {
let timer = null;
return function(...args) {
const onComplete = () => {
console.log('with apply:')
f.apply(this, args);
console.log('without apply:')
f(...args)
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
}
}
let x = {y: 1};
let deb = debounce(function() { console.log(this)}, 3);
deb.apply(x)
https://stackoverflow.com/questions/57328251
复制相似问题