1.采用闭包,可以得到一个偏函数(函数里有些参数是被固定了的),这样对于多次重复调用很有帮助,比如下面这个防抖
//模拟ajax请求
function ajax(content) {
console.log('ajax request ' + content)
}
function debounce(fun, delay) { //执行函数 延迟时间
//闭包 每一次的更新用到了fun函数和delay事件间隔
return function (args) {
//获取函数的作用域和变量
let that = this
let _args = args
//每次事件被触发,都会清除当前的timeer,然后重写设置超时调用
clearTimeout(fun.id)
fun.id = setTimeout(function () {
//在里面this和args都变了的 -->window
fun.call(that, _args)
}, delay)
}
}
//得到组件
let inputDebounce = document.getElementById('debounce')
let debounceAjax = debounce(ajax, 500)//得到一个防抖偏函数,等着输入参数
//然后被调用
//给组件添加防抖事件
inputDebounce.addEventListener('keyup', function (e) {
debounceAjax(e.target.value)
})
}
如果不采用闭包写法,那么需要在addEventListener添加的事件有三个参数,如下,很麻烦
window.onload = function () {
//模拟ajax请求
function ajax(content) {
console.log('ajax request ' + content)
}
function debounce(fun, delay, args) { //执行函数 延迟时间
//闭包 每一次的更新用到了fun函数和delay事件间隔
var that = this;
clearTimeout(fun.id)
fun.id = setTimeout(function () {
//在里面this和args都变了的 -->window
fun.call(that, args)
}, delay)
}
//得到组件
let inputDebounce = document.getElementById('debounce')
let debounceAjax = debounce(ajax, 500)//得到一个防抖偏函数,等着输入参数
//然后被调用
//给组件添加防抖事件
inputDebounce.addEventListener('keyup', function (e) {
debounce(ajax, 500, e.target.value)
})
}