我在JavaScript中使用了一些關於OOP的教程。它似乎進展順利,直到我遇到以下...訪問實例方法時發生JavaScript OO問題
Result of expression 'this.prepareFrame' [undefined] is not a function.
好的。我正在使用prototype
並使用this
關鍵字。
看到我app.js
頁這裏...
// Plain "main" function called by the html page, like <script>main()</script>. This works nicely:
function main() {
engine = new AbstractEngine();
engine.init();
}
// Next creates a new instance of my AbstractEngine class. Seems to work so far:
function AbstractEngine() {}
// The init() method we called is defined afterwards:
AbstractEngine.prototype.init = function() {
this.initLoop();
}
// remark: I'm using "this", and according to the debugger, "this" refers to the AbstractEngine we made an instance of.
// Next, we define the initLoop method:
AbstractEngine.prototype.initLoop = function() {
setInterval(this.tick, 1000/30);
}
// Fine, everything works fine so far. Now get to define the "tick" method:
AbstractEngine.prototype.tick = function() {
this.prepareFrame();
this.update();
}
// Ok, we're in trouble. The error message is output to the console and I don't understand why... The prepareFrame() and update() methods are defined right afterwards:
AbstractEngine.prototype.update = function() {
console.log('updating!');
}
AbstractEngine.prototype.prepareFrame = function() {
console.log('preparing frame');
}
// I read my code twice, but didn't find beginner's mistakes like typo or whatever. But well, cosnider I'm a beginner
你的建議解決方案不會工作,因爲''這個''改變了你的匿名函數的意義,它傳遞給了'setInterval'。看到馬特的回答。 – JAAulde
@JAAulde:????? – Domenic
嘿,謝謝你的工作答覆和解釋。我現在要消化這些信息;)謝謝! – Jem