2015-10-04 57 views
2

我正在用一個英雄人物創造一個遊戲,他的任務是收集水果遍佈畫布。對象內設置超時功能

事情是,每個水果在畫布上都有自己的到期時間。 例如,香蕉會出現5秒,橙色會出現10秒等等。

我試圖做的事情是創建一個對象,該對象的每個實例都有一個定時器,它在選定後改變布爾值時間

我的代碼看起來是這樣的:

function apple(timeToStay,score){ 
this.kind = "apple"; 
this.timeTostay = timeToStay; 
this.score=score; 
this.imgsrc = "images/apple.png"; 
this.x = 32 + (Math.random() * (canvas.width - 64)); 
this.y = 32 + (Math.random() * (canvas.height - 64)); 
this.removeMe = false; 

setTimeout(function() { this.removeMe=true; }, timeToStay*1000); 

return this; 

}

,你可以看到我以爲設置超時與實例將例如5秒後火,如果我創造了它的VAR OBJ =蘋果(5 ,5)

在開始obj.removeMe應該是假的,但5秒後應該變成真。

+2

'this'是功能範圍的。所以它在超時功能內部發生了變化。在構造函數中使用'var _this = this',在超時時使用'_this'。 – Oriol

回答

0

這應該工作:

function apple(timeToStay,score){ 
    this.kind = "apple"; 
    this.timeTostay = timeToStay; 
    this.score=score; 
    this.imgsrc = "images/apple.png"; 
    this.x = 32 + (Math.random() * (canvas.width - 64)); 
    this.y = 32 + (Math.random() * (canvas.height - 64)); 
    this.removeMe = false; 

    var base = this; 

    setTimeout(function() { base.removeMe=true; }, timeToStay*1000); 

    return this; 
} 
+0

這很糟糕,你應該總是使用bind/call/apply來解決這類問題。 –