【前端面试专栏】一篇教你从防抖、节流函数来认识this指向的文章

662 阅读1分钟

目录

防抖、节流函数在我们频繁做出某一行为(如用户input框输入或滚动事件)时会经常用到,本篇文章将带你重新认识:

  • 什么是防抖
  • 什么是节流
  • 防抖、节流函数需要注意的细节
    • 为什么需要使用fn.apply
    • 为什么要使用箭头函数
    • 不使用箭头函数如何实现
    • 哪里不能使用箭头函数

什么是防抖

防抖:行为发生一定时间后触发事件,在这段时间内如果该行为再次发生,则重新等待一定时间后再触发事件

// 防抖
function debounce(fn,time){
  let timer = null
  return function(){
    timer && clearTimeout(timer)
    timer = setTimeout(()=>{
      fn.apply(this,arguments)
    },time)
  }
}

什么是节流

节流:一段时间内如果行为多次发生,只会触发一次事件

function throttle(fn,time){
  let oldTimestamp = 0
  return function(){
    const curTimestamp = Date.now()
    if(curTimestamp - oldTimestamp >= time){
      oldTimestamp = curTimestamp
      fn.apply(this,arguments)
    }
  }
}

防抖、节流函数需要注意的细节

这里有一段demo代码

const op = document.getElementById('demo')
op.addEventListener('click',throttle(sayHi,1000))

function sayHi(){
  console.log('sayHi',this)  
}

function debounce(fn,time){
  let timer = null
  return function(){
    timer && clearTimeout(timer)
    timer = setTimeout(()=>{
      fn.apply(this,arguments)
    },time)
  }
}

接着我们继续玩下看

  • 为什么需要使用fn.apply fn.apply主要用于帮我们修改函数运行的this指向,

  • setTimeout为什么要使用箭头函数 不使用箭头函数的话,setTimeout内部this将指向window

  • setTimeout不使用箭头函数如何实现debounce

const self = this
fn.apply(self,arguments)
  • 哪里不能使用箭头函数 return function(){} !== return ()=>{} ,这里如果return一个箭头函数,内部this指向也将指向window