使用addEventListener覆盖模块中的属性时出现问题



我在将值写入addEventListener内的变量并将其用作对象属性时遇到问题。关键字this显示Player对象,但choice属性仍然为null,但在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();

它们是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,并且您在这里没有父作用域,所以它绑定到空

如果你想使用箭头函数,你必须在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
}
})
}
}
}

相关内容

最新更新