Moon
Moon

Reputation: 890

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?

Upvotes: 8

Views: 1145

Answers (1)

Jared Smith
Jared Smith

Reputation: 21926

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)
    }
 }
  

Upvotes: 6

Related Questions