radash icon indicating copy to clipboard operation
radash copied to clipboard

debounce 函数在vue3 选项式api中使用存在this指向问题

Open maodi-hub opened this issue 1 year ago • 2 comments

将debounce返回的函数赋值到methods中,执行的时候,传入的函数的this为 undefined

maodi-hub avatar Jun 20 '24 02:06 maodi-hub

Is there a solution?

HC-miss avatar Dec 14 '24 16:12 HC-miss

Two options:

  1. Use .bind()
  2. Use arrow function
class Player {
  constructor() {
    // Option 1
    this.defend = debounce({ delay: 100 }, this.defend.bind(this))
  }

  defend() {
    this.game.apply(new DefendAction(this))
  }

  // Option 2
  attack = debounce({ delay: 100 }, () => {
    this.game.apply(new AttackAction(this))
  })
}

P.S. Give the Radashi fork a try. It's an actively maintained and improved version of Radash.

aleclarson avatar Dec 14 '24 17:12 aleclarson