简体   繁体   中英

Can someone explain the 'this' in debounce function in JavaScript?

With this debounce function:

function debounce(fn, delay) {
    var timer
    return function () {
      var context = this
      var args = arguments
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn.apply(context, args)
      }, delay)
    }
  }

can someone explain why I should use fn.apply(context,args) instead of fn() only?

I know .apply will change the context and var context = this will make the context always be the same as the context in fn() . I can't find a scenario where using fn() and fn.apply(context, args) gives a different result.

Can someone give me an example?

Consider the following class:

class Foo {
  constructor () {
    this.a = 'a';
    this.bar = debounce(this.bar, 500);
  }

  bar () {
    console.log(this.a);
  }
}

const foo = new Foo();
foo.bar();
foo.bar();
foo.bar();

So what gets logged, and when, and how many times? You are going to see one value logged, one time, about half a second after the last call. With the definition you posted you'll see a . If you omit the contextual part you'll see undefined :

function debounceWithoutCtx(fn, delay) {
    var timer
    return function (...args) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn(...args)
      }, delay)
    }
 }
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM