我在vue中封装了一个防抖,使用时直接传递需要调用的方法过去,防抖功能可以实现,但我在网上看到别人写的防抖发现他们都在函数中使用了apply来调用,并且改变了this指向,让我很不解
//节流
export function throttle(callback, wait = 50) {
let timer = null
let flag = true
return function () {
if (flag) {
timer = setTimeout(() => {
callback()
flag = true
clearTimeout(timer)
timer = null
}, wait)
}
flag = false
}
}
在使用的地方
methods: {
resize() { //这个resize是我自己写的方法
this.$refs.alarmNumberBox.initWH();
this.$refs.alarmTrendBox.initWH();
this.$refs.currentQuantityBox.initWH();
this.$refs.alarmNumber.screenAdapter();
this.$refs.alarmTrend.screenAdapter();
this.$refs.alarmToday.screenAdapter();
}
},
绑定防抖处
activated() {
//保存函数
const resize = throttle(this.resize, 50);
//挂载
window.addEventListener("resize", resize);
},
我这种写法经测试不需要apply来改变this,可以实现功能,但总感觉哪里不太好,各位有空的话,请帮我看看