无法更改 JavaScript 属性 的值

Can't changing the value of JavaScript property

class Snake {
    snakeDirection = 'ArrowRight';

    constructor() {
        setInterval(() => {
            this.moveSnake();
        }, 800);

        document.addEventListener('keydown', this.changeDirection);
    }

    moveSnake() {
        console.log('moveSnake', this.snakeDirection) //ArrowRight
    }

    changeDirection(e) {
        this.snakeDirection = e.key;
        console.log('key pressed', e.key)
    }
}

let a = new Snake();

我是 javscript 的新手,正在使用 OOP 概念创建一个小项目。我试图通过调用 changeDirection 方法来更改 snakeDirection 的值,但它无法在每 800 毫秒调用一次的 moveSnake 方法中更新。 我该怎么做?

class Snake {
    snakeDirection = 'ArrowRight';

    constructor() {
        setInterval(() => {
            this.moveSnake();
        }, 800);

        document.addEventListener('keydown', this.changeDirection);
    }

    moveSnake() {
        console.log('moveSnake', this.snakeDirection) //ArrowRight
    }

    changeDirection(e) {
        this.snakeDirection = e.key;
        console.log('key pressed', e.key)
    }
}

let a = new Snake();

这是我发现的问题 this.snakeDirection 无法使用,因为它不在构造方法中。仅使用 snakeDirection = e.key。 我的意思是它不是class的属性,它只是一个class变量,不能用作class 属性。 Class变量和class属性是两个不同的概念。

您必须将参数(事件)传递给 func。

const snake = new Snake();
document.addEventListener('keydown', e => snake.changeDirection(e));

这是 setInterval 的上下文问题。如果您将方法更改为 class 属性(基本上是箭头函数),以便正确理解 this,问题就会消失。

class Snake {

  snakeDirection = 'ArrowRight';
  
  constructor() {
    document.addEventListener('keydown', this.changeDirection);
    setInterval(this.moveSnake, 800);
  }
  
  moveSnake = () => {
    console.log('moveSnake', this.snakeDirection);
  }

  changeDirection = (e) => {
    console.log(e.key)
    this.snakeDirection = e.key;
  }

}

let a = new Snake();

错误的原因是 'this' 在函数 changeDidrection 中不是对象 a。它是对象文档。 所以,Either listener set out of class

class Snake {
            
        
            constructor() {
                setInterval(() => {
                    this.moveSnake();
                }, 800);
                this.snakeDirection = 'ArrowRight';
                document.addEventListener('keydown', changeDirection);
            }
        
            moveSnake() {
                console.log('moveSnake', this.snakeDirection) //ArrowRight
            }
            
        }
        
        let a = new Snake();
        function changeDirection(e) {
            a.snakeDirection = e.key;
            console.log('key pressed', e.key)
        }

或者使用箭头函数

changeDirection = (e) => {
            console.log(e.key)
            this.snakeDirection = e.key;
          }