我正在尝试通过定期替换其内部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对象的上下文。

09-16 17:49