使用setInterval

时间:2016-05-11 04:31:00

标签: javascript jquery function prototype setinterval

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

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

我最初使用" var privateVars< - > this.methods"没有多少问题,但切换到" this.publicVars< - > Class.prototype.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();

任何帮助或建议将不胜感激。但是,如果它包含计时器,那么我认为原型是不可取的。

3 个答案:

答案 0 :(得分:1)

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

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

如果您未明确绑定上下文,则this内的getUpdates上下文将指向窗口。因此window.updateInterval将是undefined

答案 1 :(得分:0)

您可以使用bindthis函数中设置getUpdates上下文:

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

Working example

答案 2 :(得分:0)

您可以将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);
    });
};
相关问题