我需要类中事件侦听器方法内的“多个范围”(“this”范围)JavaScript 拖放 API

问题描述 投票:0回答:1

(我是 JS 新手)

我正在编写一个 Web 应用程序,该应用程序包含一个 4x4 的表格,其中包含从 1 到 15 的数字部分和一个空格。

我正在摆弄 drag&drop API,然后我注意到 我的事件侦听器方法与其他方法具有不同的范围。

示例代码

class game() {
  // constructors and a bunch of methods
  
  this.4x4table = [...] // One variable that I need to access

  // My problematic method here
  handleDrop(ev) {
    // Basically grabbing info from handleDrag dataTransfer and changing the target
    // element with the source element

    // There is no problem with above, but the problem starts when I try to update my
    // 4x4 grid representation of the game (a 2D array in the class game)

    this.4x4table[0][0] // Cant reach
  }
}

我尝试使用箭头函数,但后来我不知道如何访问我之前使用“this”访问的目标元素变量。

javascript drag-and-drop this event-listener
1个回答
0
投票

我认为这会起作用:

使用箭头函数,例如:

handleDrop = ev => { ... }

将使“this”的范围成为类范围。如果您需要访问拖动的内容,您可以使用“ev”参数来访问它

// Will print element dragged    
console.log(ev.srcElement)
© www.soinside.com 2019 - 2024. All rights reserved.