我在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,可以实现功能,但总感觉哪里不太好,各位有空的话,请帮我看看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function throttle(callback, wait = 50) {
let timer = null
let flag = true
return function () {
const _this = this
if (flag) {
timer = setTimeout(() => {
// callback()
callback.apply(_this)
flag = true
clearTimeout(timer)
timer = null
}, wait)
}
flag = false
}
}
const person = {
name:"小明",
say:function(){
console.log(this.name + '说话了')
}
}
window.name = '小红'
person.say()
const test = throttle(person.say, 50);
window.addEventListener("resize", test.bind(person));
</script>
</body>
</html>
在Vue中methods的 this 自动绑定为 Vue 实例,内部可能做了什么处理,这个不太清楚
因为return function () {}属于匿名函数,加上apply可以根据使用者需要修改this指向,为了代码的健全性,并不推荐去除