有人可以解释 JavaScript 中 debounce 函数中的“this”吗?

Moo*_*oon 6 javascript debouncing

有了这个debounce功能:

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

有人可以解释为什么我应该使用fn.apply(context,args)而不是fn()仅仅使用吗?

我知道.apply会改变上下文var context = this并使上下文始终与fn(). 我找不到使用fn()fn.apply(context, args)给出不同结果的场景。

有人可以举个例子吗?

Jar*_*ith 6

考虑下面的类:

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();
Run Code Online (Sandbox Code Playgroud)

那么什么会被记录,什么时候记录,记录多少次?在最后一次调用后大约半秒,您将一次看到记录的一个值。根据您发布的定义,您会看到a. 如果省略上下文部分,您将看到undefined

function debounceWithoutCtx(fn, delay) {
    var timer
    return function (...args) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn(...args)
      }, delay)
    }
 }
  
Run Code Online (Sandbox Code Playgroud)