从对象内部调用对象函数的SetInterval

SetInterval on functions of an object from within the object

本文关键字:对象 SetInterval 函数 调用 内部      更新时间:2023-09-26

我试图通过定期替换其内部HTML来创建一个可以在<div>上工作的对象。不过,我被"周期性"这个词难住了。这就是我要做的(代码的相关部分,我省略了不相关的声明等):

function LedDisplay() {
    this.initialize() {
        window.setInterval(this.redraw, 200);
    };
    this.redraw = function() {
        this.shiftDisplayMatrix();
        $('#' + this.name).html(this.createSvg());
    };
    this.shiftDisplayMatrix = function() {
        var firstRow = this.displayMatrix[0];
        this.displayMatrix.splice(0, 1);
        this.displayMatrix.push(firstRow);
    };
};

结果如下- this.shiftDisplayMatrix is not a function。我相信这是因为redraw在全局环境中被调用,而那里没有this.shiftDisplayMatrix。我似乎找不到的是如何达到我想要的。

或者我正在尝试做的是一个反模式?

是的,因为调用this.shiftDisplayMatrix的上下文不再是对象本身,它不再具有访问函数的权限。你可以试试

function LedDisplay() {
    var self = this;
    ....
}

,然后调用self.shiftDisplayMatrix,在这里我们使用self来保存LedDisplay对象的上下文