Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用addEventListener覆盖模块中的属性时出现问题_Javascript_Scope_This_Addeventlistener - Fatal编程技术网

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

Javascript 使用addEventListener覆盖模块中的属性时出现问题,javascript,scope,this,addeventlistener,Javascript,Scope,This,Addeventlistener,在addEventListener中将值写入变量并将其用作对象属性时遇到问题。这个关键字显示了Player对象,但是choice属性仍然为null,但是在addEventListener中一切正常。对不起,我英语不好,但我真的需要帮助 export class Player{ constructor(){ this.board = document.querySelector('.playerMoveImg'); this.score = 0; this.choice =

在addEventListener中将值写入变量并将其用作对象属性时遇到问题。这个关键字显示了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
}
}


它们是
方法
语法和
箭头函数
语法之间的差异

导出类播放器{
构造函数(){
this.board=document.querySelector('.playerMoveImg');
这个分数=0;
this.choice=null;
}
//而不是moveChoice=()=>{
//使用:
moveChoice(){
const localChoise=document.addEventListener('单击',(事件)=>{
if(event.target.value!==未定义){
this.choice=event.target.value;
this.board.style.backgroundImage=`url(“src/img/Player${this.choice}.jpg”)`;
console.log(this.choice);//我们需要将此日志移到回调中
}
})
}
}
问题是,由于它在arrow函数中绑定到父
this
,并且您在这里没有父作用域,因此它被绑定为null

如果要使用arrow函数,必须在调用
构造函数期间设置方法:

导出类播放器{
构造函数(){
this.board=document.querySelector('.playerMoveImg');
这个分数=0;
this.choice=null;
this.moveChoice=()=>{
//在这种情况下,arrow函数可以找到这个父对象
//它将使用与构造函数相同的一个
const localChoise=document.addEventListener('单击',(事件)=>{
if(event.target.value!==未定义){
this.choice=event.target.value;
this.board.style.backgroundImage=`url(“src/img/Player${this.choice}.jpg”)`;
console.log(this.choice);//显示空//预期显示event.target.value
}
})
}
}
}

请始终使用相应的编程语言标记,以便吸引更多定制的观众,而其他可能在相关技术方面没有能力的人将看不到您的问题。不幸的是,在您进行更改后,它仍然显示为空。然后我需要查看您调用的代码
moveChoice
我已经看过了我尝试使用该解决方案将函数移动到构造函数,但不幸的是,它不起作用。哦,我明白了,问题是您的console.log是在任何单击注册之前完成的,因此它将始终为
null
。好的,我明白,但如何让对象记住addEventListener中的值
import {Player} from './player.js'
const player = new Player();
player.moveChoice();