JS类我如何知道如何使用self或this

时间:2018-10-16 01:21:47

标签: javascript

我有一个处理对象某些运动的类对象。在mouseMove中,所有变量都必须是self,甚至是paddleWidth之类的静态值,但在移动功能中,this关键字才是paddleWidth的静态值。有人可以帮助我了解如何知道何时应该使用自我吗?

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;
        }
    };
  }

0 个答案:

没有答案