我正在用javascript制作一個簡單的游戲,你可以向敵人發射子彈。實際上我沒有任何問題,但是:
我為我的子彈創建了一個類,它有一個Move函式,我想為它設定一個間隔,但是當我在我的建構式中設定一個間隔時,如下所示:
setInterval(this.Move, 0);
我看到這個錯誤:
未捕獲的型別錯誤:無法在移動 (game.js:152) 時讀取未定義的屬性(讀取“樣式”)
但是當我像這樣設定和反轉時:
setInterval(() => {
this.Move();
}, 0);
它可以毫無問題地作業。
我只是想知道第一個有什么問題,我認為第二種方式,你正在做一個額外的事情(lambda 運算式)。
子彈類:https : //i.stack.imgur.com/q23Lk.png
uj5u.com熱心網友回復:
這是個好問題。主要區別在于箭頭函式的使用。箭頭函式旨在系結到定義它們的作用域。
通過簡單地傳遞this.Moveto setInterval,setInterval將呼叫函式而不系結到類/實體范圍。
下面的代碼演示了您可以傳遞this.Move給setInterval. 有些有正確的范圍,有些沒有,希望這會幫助你理解。
let outside_function = undefined;
class X {
constructor() {
this.message = 'moving'
// function is not bound to instance
setInterval(this.move, 1000); // undefined
// function is bound to instance
setInterval(this.move.bind(this), 1000) // 'moving'
// arrow function binds to 'this'
setInterval(() => this.move(), 1000) // 'moving'
// outside_function has no relationship with the class
outside_function = this.move;
setInterval(outside_function, 1000); // undefined
setInterval(outside_function.bind(this), 1000) // 'moving'
}
move() {
console.log(this.message)
}
}
// also note that we can call the function like this
// again, no class instance here
X.prototype.move() // undefined
new X();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318485.html
標籤:javascript 功能 哎呀 设置间隔 子弹
上一篇:Python嵌套函式中的可選引數
下一篇:如何在Click功能上克隆專案?
