【问题标题】:Problem with overwriting property in module with addEventListener使用 addEventListener 覆盖模块中的属性的问题
【发布时间】:2020-12-25 02:49:32
【问题描述】:

我在将值写入 addEventListener 内的变量并将其用作对象属性时遇到问题。关键字 this 显示 Player 对象,但选择属性仍然为空,但在 addEventListener 内一切正常。抱歉我的英语不好,但我真的需要帮助。

export class Player{
constructor(){
    this.board = document.querySelector('.playerMoveImg');
    this.score = 0;
    this.choice = null;
}
moveChoice = () => {
    const localChoise = document.addEventListener('click',(event)=>{
        if(event.target.value !== undefined){
            this.choice = event.target.value;
            this.board.style.backgroundImage =`url("src/img/Player${this.choice}.jpg")`;
        }
    })
    console.log(this.choice); //shows null //expect showing event.target.value
}

}

import {Player} from './player.js'
const player = new Player();
player.moveChoice();

【问题讨论】:

  • 请始终使用相应的编程语言标签,以吸引更多量身定制的受众,而其他可能对相关技术没有能力的人不会看到您的问题。

标签: javascript scope this addeventlistener


【解决方案1】:

它们是method 语法和arrow function 语法之间的区别。

export class Player{
  constructor(){
    this.board = document.querySelector('.playerMoveImg');
    this.score = 0;
    this.choice = null;
  }
  // instead of moveChoice = () => {
  // use:
  moveChoice() {
    const localChoise = document.addEventListener('click',(event)=>{
      if (event.target.value !== undefined){
        this.choice = event.target.value;
        this.board.style.backgroundImage =`url("src/img/Player${this.choice}.jpg")`;

        console.log(this.choice); // we need to move this log into the callback
      }
    })
  }
}

问题在于,由于 this 在箭头函数中绑定到父级 this,而您在这里没有父级作用域,所以它被绑定为 null

如果你想使用箭头函数,你必须在constructor调用期间设置方法:

export class Player{
  constructor(){
    this.board = document.querySelector('.playerMoveImg');
    this.score = 0;
    this.choice = null;
    this.moveChoice = () => {
      // in this case, the arrow function can find the parent this
      // it will use the same one as the constructor
      const localChoise = document.addEventListener('click',(event)=>{
        if (event.target.value !== undefined){
          this.choice = event.target.value;
          this.board.style.backgroundImage =`url("src/img/Player${this.choice}.jpg")`;

          console.log(this.choice); //shows null //expect showing event.target.value
        }
      })
    }
  }
}

【讨论】:

  • 不幸的是,在您更改后它仍然显示为 null。
  • 那我需要看看你调用moveChoice的代码
  • 我已经尝试使用该解决方案将函数移动到构造函数但不幸的是它不起作用。
  • 哦,我明白了,问题是您的 console.log 在任何点击注册之前就完成了,所以它总是null
  • 好的,我明白了,但是如何让对象记住来自 addEventListener 的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2020-12-02
  • 2016-07-20
相关资源
最近更新 更多