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 的新手,并使用 OOPs 概念創建了一個小專案。我正在嘗試通過呼叫 changeDirection 方法來更改snakeDirection 的值,但它無法在每800ms 呼叫一次的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();
uj5u.com熱心網友回復:
您必須將引數(事件)傳遞給 func。
const snake = new Snake();
document.addEventListener('keydown', e => snake.changeDirection(e));
uj5u.com熱心網友回復:
這是我發現this.snakeDirection無法使用的問題,因為它不在建構式方法中。只使用snakeDirection = e.key.
uj5u.com熱心網友回復:
這是一個背景關系問題setInterval。如果您將方法更改為類屬性(基本上是箭頭函式)以便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();
uj5u.com熱心網友回復:
錯誤的原因是函式 changeDidrection 中的“this”不是物件 a。它是物件檔案。所以,任何一個聽眾都離開了課堂
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/455014.html
標籤:javascript 班级 目的 哎呀
