2015-10-11 46 views
0

我試圖通過定期替換它的內部HTML來創建將在<div>上工作的對象。儘管如此,我很難定期對這部分內容進行評論。這就是我想要做的(代碼中的相關部分,我省略unrelevant聲明等):對象從對象中的函數的SetInterval

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。我似乎無法找到的是如何實現我想要的。

或者我想要做的是反模式?

回答

1

是的,因爲調用this.shiftDisplayMatrix的上下文不再是對象本身,它不再有權訪問該函數。你可以嘗試做的是

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

,然後調用self.shiftDisplayMatrix,在這裏我們使用的自我拯救發光二極管顯示器對象的上下文。

相關問題