Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【javascript】一篇教你从防抖、节流函数来认识this指向的文章 #31

Open
AwesomeDevin opened this issue Apr 28, 2020 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

AwesomeDevin commented Apr 28, 2020

目录

防抖、节流函数在我们频繁做出某一行为(如用户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指向, 否则this将指向window

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

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

const self = this
fn.apply(self,arguments)
  • 哪里不能使用箭头函数
    return function(){} !== return ()=>{} ,这里如果return一个箭头函数,内部this指向也将指向window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant