所以我有以下代码:
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)时,”square将不会移动,因为移动函数中的“this”指向“document”对象。当我尝试用箭头函数修复它时(如上面的代码所示),“this”正确指向方形对象但是它也不会移动,因为方形对象没有“which”属性而我无法使用它扫描密钥代码。原谅我,如果这是一个简单的解决方案的愚蠢问题,但我是新手程序员。我在事件处理程序中已经阅读了相关的相关主题,但我找不到一个ansewr。
答案 0 :(得分:1)
当前设置的最快速修复方法是在箭头函数中传递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);
答案 1 :(得分:0)