gpt4 book ai didi

使用类方法调用 Javascript 事件监听器

转载 作者:行者123 更新时间:2023-12-03 06:37:31 25 4
gpt4 key购买 nike

所以我有以下代码:

class SquareBlock {
constructor(){
this.startPosition = rand(1, boardHeight - 3);
this.block = [{x: 1, y: this.startPosition}];
this.block.push({x: 1, y: this.startPosition + 1});
this.block.push({x: 2, y: this.startPosition});
this.block.push({x: 2, y: this.startPosition + 1});

document.addEventListener('keydown', () => {return this.move();}, true);

for(var n in this.block){
fields[getFieldId(this.block[n].x, this.block[n].y)].hasBlock = true;
pointColor(this.block[n].x, this.block[n].y, 'blue');
}

this.start();
}

start(){
for(var n in this.block){
fields[getFieldId(this.block[n].x, this.block[n].y)].hasBlock = false;
pointColor(this.block[n].x, this.block[n].y, 'transparent');
}
for(var n in this.block){
this.block[n].x += 1;
}
for(var n in this.block){
fields[getFieldId(this.block[n].x, this.block[n].y)].hasBlock = true;
pointColor(this.block[n].x, this.block[n].y, 'blue');
}

if(this.isSettledValidate() != 'stop'){
setTimeout(() => {this.start()}, 100);
}
}

isSettledValidate(){
if(this.block[2].x == boardWidth - 2 || this.block[3].x == boardWidth - 2){
return 'stop';
}
if(fields[getFieldId(this.block[2].x + 1, this.block[2].y)].hasBlock == true){
return 'stop';
}
if(fields[getFieldId(this.block[3].x + 1, this.block[3].y)].hasBlock == true){
return 'stop';
}
}

move(ev){
switch(ev.which){
case 37:
for(var n in this.block){
if(this.block[n].y - 1 != 0){
this.block[n].y -= 1;
}
}
break;
case 39:
for(var n in this.block){
if(this.block[n].y + 1 != boardHeight - 1){
this.block[n].y += 1;
}
}
break;
}
}

}

我在构造函数中遇到了 document.addEventListener 的问题。我想要实现的是使用 move() 类方法将 SquareBlock 向左或向右移动一个空格。当我使用代码“document.addEventListener('keydown', move, true)”时,方 block 不会移动,因为移动函数中的“this”指向“document”对象。当我尝试使用箭头函数(如上面的代码)修复此问题时,“this”正确指向方形对象,但它也不会移动,因为方形对象没有“which”属性,我无法使用它扫描键码。如果这是一个简单解决方案的愚蠢问题,请原谅我,但我是新手程序员。我在事件处理程序中阅读了有关此内容的相关主题,但在那里找不到答案。

最佳答案

当前设置最快的快速修复方法是在箭头函数中传递 eventargs:e => this.move(e):

document.addEventListener('keydown', e => this.move(e), true);

测试的简化示例:

class SquareBlock {
constructor(){
document.addEventListener('keydown', e => this.move(e), true);
}

move(ev){
console.log(this , ev);
}
}

new SquareBlock();
<小时/>

或者,您可以bind功能:

document.addEventListener('keydown',this.move.bind(this), true);  

关于使用类方法调用 Javascript 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38122497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com