外部调用一个函数,该函数return一个函数,return的函数不执行,代码如下:
//防抖
function debounce (fn, delay = 1000) {
let time = null
return function () {
// 获取当前this
let that = this
// 判断是否已经存在,如果存在直接清除
if (time) {
clearTimeout(time)
}
time = setTimeout(() => {
// 使fn 中this,执行当前调用者,并传入参数
fn.apply(that, arguments);
}, 100)
})()
}
因为return的是function,外部访问的时候必须加上括号,不然得到的是function本身的内容,但不执行。如果要得到return后的函数,就是要得到debounce()(),而不是debounce(), 所以return的函数必须加上括号。
代码修改如下:
//防抖
function debounce (fn, delay = 1000) {
let time = null
// 因为return的是function,外部访问的时候必须加上括号,不然得到的是function本身的内容,但不执行
return (function () {
// 获取当前this
let that = this
// 判断是否已经存在,如果存在直接清除
if (time) {
clearTimeout(time)
}
time = setTimeout(() => {
// 使fn 中this,执行当前调用者,并传入参数
fn.apply(that, arguments);
}, 100)
})()
}
执行成功