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

标签 javascript oop this prototype-programming

我已经使用了一些关于 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/

相关文章:

c++ - noexcept 规范中是否允许使用 `this`?

javascript - 有没有办法在使用 ES6 速记方法表示法的方法中包含词法 `this` ?

javascript - jQuery - 调整浏览器窗口大小后自动更改值

javascript - 在一台工作站中模拟同源策略

javascript - AngularJS $http.post 调用返回 502(坏网关)错误

oop - 好的设计模式系统重写?

javascript - 如何在框架集中的 iframe 中更改 CSS

c# - 让业务逻辑对象提示用户输入是不是糟糕的设计?

java - 避免在通用工厂方法中出现 ClassCastException

c++ - 为什么有些类方法返回 "*this"(自身的对象引用)?