2017-02-13 59 views
1

我在Javascript中的setInterval()方法有問題。我的主類:Javascript setInterval不適用於此。對象

var sq1 = new Square(20, 20); 
window.onkeydown = function (e) 
{ 
    var key = e.keyCode ? e.keyCode : e.which; 
    if (key == 38) 
    { 
     sq1.moveUp(); 
    } 
} 

而且我有以下構造函數。

function Square(x,y) 
{ 
    var multiplicator = 10; 

    this.xPos = x; 
    this.yPos = y; 

    this.domObj = document.createElement("div"); 
    this.domObj.style.position = "absolute"; 
    this.domObj.style.left = this.xPos * multiplicator + 'px'; 
    this.domObj.style.top = this.yPos * multiplicator + 'px'; 
    this.domObj.style.width = multiplicator + 'px'; 
    this.domObj.style.height = multiplicator + 'px'; 
    this.domObj.style.backgroundColor = "black"; 
    document.getElementById("idCanvas").appendChild(this.domObj); 

    this.moveUp = function() 
    { 
     this.yPos--; 
     this.domObj.style.top = (this.yPos * multiplicator) + 'px'; 
    } 
} 

那麼現在正常工作,只需將每個keyUp事件移動10px即可。 但是我想在keyUp事件之後每1000個毫秒自動調用一次this.moveUp()。 但當我嘗試這個辦法:

this.moveUp = function() 
{ 
    setInterval(function() 
    { 
     this.yPos--; 
     this.domObj.style.top = (this.yPos * multiplicator) + 'px'; 
    }, 1000); 
} 

我得到一個錯誤,「這是空值。

我該如何解決它(最好沒有jQuery)?

回答

1

您需要的的setInterval到同一目標結合爲你的類。

this.moveUp = function() 
{ 
    setInterval(function() 
    { 
     this.yPos--; 
     this.domObj.style.top = (this.yPos * multiplicator) + 'px'; 
    }.bind(this), 1000); 
} 
+0

向下投票吧?以爲我做得對,但也許不是? – Ribs

+0

不是「範圍」而是「目標」。另外,不涉及任何課程。 – Ben

+0

是的,我知道沒有類,但我雖然爲了清晰起見,我會使用OP使用的相同條款。 – Ribs

1

的目標是內部setInterval

Window對象要麼你需要捕獲詞彙範圍,並使用它,或者使用bind硬綁定的對象引用處理程序setInterval範圍內。

使用詞彙範圍

this.moveUp = function() { 
    // capturing the lexical scope 
    var self = this; 
    setInterval(function() { 
    self.yPos--; 
    self.domObj.style.top = (self.yPos * multiplicator) + 'px'; 
    }, 1000); 
} 

使用綁定

this.moveUp = function() { 
    setInterval(function() { 
    this.yPos--; 
    this.domObj.style.top = (this.yPos * multiplicator) + 'px'; 
    }.bind(this) , 1000); 
} 
+1

你在JavaScript中有一個金徽章;當然,你知道這是許多問題的重複? –

+0

假設你不需要IE 8和以下的支持,是否有任何理由*不*在這個實例中使用'.bind()'? –

+0

@MikeMcCaughan大多數解決方案都是非常通用的,它需要在理解它之前掌握整個內容。認爲給出一個簡約的例子會幫助OP,因爲他是JS的新手。 –