防抖处理this的两种方式
// 防抖函数
export const debounce = function (func, wait = 1000) {
let timeout = null;
// 使用箭头函数
return function () { //如果这里return箭头函数,则没有this,会向上查找this,找到window
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => { //这里又必须是箭头函数,不然this指向window
func.apply(this)
}, wait)
}
// 不使用箭头函数
return function () {
let _this = this;
let arg = arguments;
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(function () {
// apply(thisArg, argsArray)
// thisArg 在 func 函数运行时使用的 this 值
// argsArray 可选 一个数组或者类数组对象
func.apply(_this, arg)
}, wait)
}
}