I have a class object that handles some movement for an object. In the mouseMove all the variables need to be a self
even the static values like paddleWidth
but in the movement function the this
key word worked for the static values of paddleWidth
. Could someone help me understand how to know when self should be used instead of this?
export class Paddle {
constructor (world) {
var self = this;
this.canvas = world.canvas;
this.ctx = world.ctx;
this.paddleHeight = 10;
this.paddleWidth = 75;
this.paddleX = (this.canvas.width - this.paddleWidth) / 2; // location
this.rightPressed = false;
this.leftPressed = false;
this.keyDownHandler= function(e) {
if (e.keyCode == 39) {
self.rightPressed = true;
}
else if (e.keyCode == 37) {
self.leftPressed = true;
}
};
this.keyDown = document.addEventListener("keydown", this.keyDownHandler, false);
this.keyUpHandler= function(e) {
if (e.keyCode == 39) {
self.rightPressed = false;
}
else if (e.keyCode == 37) {
self.leftPressed = false;
}
};
this.keyUp = document.addEventListener("keyup", this.keyUpHandler, false);
this.mouseMoveHandler = function(e) {
console.log('mouseMove', this.paddleX)
var relativeX = e.clientX - self.canvas.offsetLeft;
if(relativeX > 0 && relativeX < self.canvas.width){
self.paddleX = relativeX - self.paddleWidth/2
}
};
this.mouseMove = document.addEventListener("mousemove", this.mouseMoveHandler, false);
this.movement= function() {
console.log('movement', this.paddleX)
if (this.rightPressed && this.paddleX < this.canvas.width - this.paddleWidth) {
self.paddleX += 7;
} else if (this.leftPressed && this.paddleX > 0) {
self.paddleX -= 7;
}
};
}