大家好,我有这个代码
class Player {
constructor(posX, posY, spdX, spdY, width, height, image){
// Vytvoření hráče
this.posX = posX;
this.posY = posY;
this.spdX = spdX;
this.spdY = spdY;
this.width = width;
this.height = height;
this.image = image;
}
// Draws player
draw(){
var imageObj = new Image();
imageObj.src = this.image;
ctx.drawImage(imageObj, testPlayer.posX, testPlayer.posY);
}
jump(){
this.move('up');
}
// Move
move(direction){
// Returns false if fails
switch(direction){
case 'right':
this.posX+= this.spdX;
break;
case 'left':
this.posX-= this.spdX;
break;
case 'up':
this.posY-= this.spdY;
break;
case 'down':
this.posY+= this.spdY;
break;
default:
return false;
}
}
}
我的跳转方法有问题。
当我想跳的时候,我必须上下跳动,但是过了一段时间之后我怎么能跳呢?
因为我尝试 setTimeout(function(){})
但在该 function 关键字内看不到方法移动。如果我这样做 setTimeout(this.move('down'),500)
它不起作用。那么有什么想法吗?
最佳答案
您需要该函数具有正确的上下文。一种简单的方法是使用 ES6 箭头函数 ( caniuse )。它们将保留您最初定义函数时的 this
上下文:
setTimeout(()=>{this.move('down')}, 500)
或者,如果您想使用常规函数,请使用 Function.prototype.bind() 绑定(bind) this
上下文。这样,当最终调用该函数时,上下文就是调用 .bind(this) 时的 this
function goDown(){this.move('down')}
setTimeout(goDown.bind(this))
关于Javascript OOP 可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658324/