使用 setInterval 调用原型函数的问题

Issue with calling a prototype function with setInterval

我制作了 Bot 的原型 class。我的问题是,在创建它之后,我将其称为 init()。它在警报中正确 returns 这个值 "a 5000"。但是,当该原型函数调用 getUpdates() 时,它不再达到此值并给出 "b undefined"。我什至试过 this.self = this;在构造函数中但没有运气。

经过努力,我发现在 setInterval 的 self.getUpdates 调用上添加 () 使其正确获取值然后另一个问题,setInterval 只循环一次。我试过制作一个 setTimeout 并让它在 getUpdates 中调用自己但是得到了 "too much recursion script.js:30:1"。我有时 "uncaught exception: out of memory "

我最初使用 "var privateVars <-> this.methods" 没有太大问题,但后来改用 "this.publicVars <-> Class.prototype.methods",因为我读过它们应该更快,内存更少,但这种原型方法给我带来了问题。我试过浏览 Google 但没有成功。我希望在 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();

如有任何帮助或建议,我们将不胜感激。但我认为如果原型包含计时器,则不是可行的方法。

您必须 bind this 上下文正确地引用函数,

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

如果您没有显式绑定上下文,那么 getUpdates 中的 this 上下文将指向 window。所以 window.updateInterval 将是 undefined.

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

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

Working example

您可以将 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);
    });
};