Reputation: 301
Hi guys I have this code
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;
}
}
}
I have problem in jump method.
When I want to jump I must go up and down, but how can I do that after time.
Because I tried to setTimeout(function(){})
but inside that function keyword this cant see method move. And if I do setTimeout(this.move('down'),500)
it doesnt work. So any ideas ?
Upvotes: 2
Views: 113
Reputation: 3478
You need the function to have the correct context. One simple way would be to use ES6 arrow functions (caniuse). They will preserve the this
context from when you originally defined the function:
setTimeout(()=>{this.move('down')}, 500)
Or if you want to use regular functions, use Function.prototype.bind() to bind the this
context. This way, when the function is eventually called, the context is the this
from when you called .bind(this)
function goDown(){this.move('down')}
setTimeout(goDown.bind(this))
Upvotes: 2
Reputation: 20007
The problem is that setTimeout
's callback
causes the value of this
to change.
You can preserve this
by doing:
var that = this;
setTimeout(function () {
that.move('down');
}, 500);
Upvotes: 1