【问题标题】:Can someone explain the 'this' in debounce function in JavaScript?有人可以解释 JavaScript 中 debounce 函数中的“this”吗?
【发布时间】:2021-01-31 06:47:49
【问题描述】:

有了这个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)
    }
  }

有人能解释一下为什么我应该只使用fn.apply(context,args) 而不是fn() 吗?

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

谁能给我一个例子?

【问题讨论】:

  • 显然,您必须这样做,因为您想在调用者上下文中执行函数。 javascript.info
  • 否则你不能使用 debounce 来装饰对象方法。
  • 您不需要使用thisapply,除非您正在使用类/原型/对象方法。如果你不使用this,你可以按照你的建议去做。

标签: javascript debouncing


【解决方案1】:

考虑以下类:

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();

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 2015-09-10
    • 2016-03-14
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多