gpt4 book ai didi

访问实例方法时的 JavaScript OO 问题

转载 作者:行者123 更新时间:2023-11-30 09:02:56 24 4
gpt4 key购买 nike

我已经使用了一些关于 JavaScript 中的 OOP 的教程。似乎一切顺利,直到我遇到了以下......

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

最佳答案

您需要将 initLoop 的定义更改为以下内容:

AbstractEngine.prototype.initLoop = function() {
var that = this;

setInterval(function () {
that.tick();
}, 1000 / 30);
}

这是因为this的解析延迟到执行时间,当interval执行时,this指向window,而不是您的 AbstractEngine 实例。

通过在匿名函数中包装对 tick 的调用,我们创建了一个闭包,它允许我们捕获 that(我们将其设置为 this).通过在 instance 上调用 method tick(这是 old this),我们可以恢复值“这个”)。

关于访问实例方法时的 JavaScript OO 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7714071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com