使用setInterval调用原型函数时出现问题

Issue with calling a prototype function with setInterval

本文关键字:问题 函数 setInterval 调用 原型 使用      更新时间:2023-09-26

我制作了一个Bot的原型类。我的问题是,在创建它之后,我调用它的init()。它在警报中正确地返回此值"a 5000"。然而,当该原型函数调用getUpdates()时,它不再达到该值并给出"b undefined"。我甚至试过这个。self=这个;在构造函数中,但没有运气。

经过努力,我发现在setInterval中的self.getUpdates调用上添加()使其正确地获得了值,然后是另一个问题,setInterval只循环一次。我试过创建一个setTimeout,并在getUpdates中调用它自己,但得到了"太多递归脚本.js:30:1"。有时我会得到"未捕获的异常:内存不足"

我最初使用的是"varprivateVars<->this.methods",没有太多问题,但后来改为"this.publicVars<->Class.protype.methods",因为我读到它们应该更快、内存更少,但这个原型方法给了我问题。我试过浏览谷歌,但没有成功。我更喜欢在init()上启动计时器。

这是我的代码:

var Bot = function () {
    "use strict";
    this.updateInterval = 5000;
    this.updateTimer = null;
};
Bot.prototype.getUpdates = function () {
    "use strict";
    var self = this;
    alert("b " + self.updateInterval); // returns "b undefined"
};
Bot.prototype.init = function () {
    "use strict";
    var self = this;
    $.get(/* pretend url is here*/, function (data, status) {
        alert("a " + self.updateInterval); // returns "a 5000"
        self.updateTimer = setInterval(self.getUpdates, self.updateInterval);
    });
};
window.bot = new Bot();
window.bot.init();

如有任何帮助或建议,我们将不胜感激。但我认为,如果原型包括计时器,就不可能实现。

您必须将bindthis上下文正确地连接到函数引用

self.updateTimer = setInterval(self.getUpdates.bind(self), self.updateInterval);

若不显式绑定上下文,则getUpdates内部的this上下文将指向窗口。所以window.updateInterval将是undefined

您可以使用bindgetUpdates函数中设置this上下文:

self.updateTimer = setInterval(self.getUpdates.bind(self), self.updateInterval);

工作示例

您可以将Bot的this引用发送到getUpdates函数。

Bot.prototype.getUpdates = function (self) {
    "use strict";
    alert("b " + self.updateInterval); 
};
Bot.prototype.init = function () {
    "use strict";
    var self = this;
    $.get(/* pretend url is here*/, function (data, status) {
        alert("a " + self.updateInterval);
        self.updateTimer = setInterval(self.getUpdates(self), self.updateInterval);
    });
};