javascript - 从对象内部对对象的函数设置间隔

标签 javascript jquery

我正在尝试创建一个可在 <div> 上运行的对象通过定期替换其内部 HTML。不过,我对“定期”这部分感到困惑。这就是我想要做的(代码的相关部分,我省略了不相关的声明等):

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 对象的上下文。

关于javascript - 从对象内部对对象的函数设置间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33060271/

相关文章:

javascript 变量使用帮助

javascript - 在 <form> 之外输入标签并提交表单

javascript - 如何防止历史记录在计算器中消失

javascript - 什么是 gatsbyContentfulFluid?

javascript - Angular JS : Add class to element

Javascript Wscript.Shell 命令无法通过单击浏览器中的按钮来运行

javascript - 无法创建简单的文本幻灯片

javascript - Electron - 断点仅在 main.js 中有效,但在 index.js 中无效

javascript - 将两个图像拖在一起,但将移动限制在垂直轴上

javascript - 如何在 Eclipse 中测试和创建 angularjs 的测试用例?