2017-09-17 51 views
0

我遇到問題。每當我嘗試創建Candy函數的對象時,所有屬性似乎都創建得很好。但是,每當我嘗試運行draw函數時,都會使用最新創建的對象的所有屬性,而不是我正在使用的那個。它總是會繪製我創建兩次的第二個對象,但永遠不會是第一個。我不知道爲什麼。我嘗試了所有的方法來解決這個問題,所以如果在代碼中看起來效率很低,那可能是我試圖解決這個問題的很多嘗試之一。你們知道這個問題嗎?Javascript - 對象中的函數中的屬性還原爲最新創建的對象

下面是糖果函數的代碼:

Candy = function(img, location, canvas) { 
 
\t self = {} 
 
\t self.image = new Image() 
 
\t self.image.src = img 
 
\t self.location = {x: location.x, y: location.y} 
 
\t self.canvas = canvas 
 
\t self.draw = function() { 
 
\t \t self.canvas.drawImage(self.image, self.location.x, self.location.y, 132.4, 132.4) 
 
\t } 
 
\t self.move = function(FPS, seconds, location) { 
 
\t \t frames = FPS * seconds 
 
\t \t deltaX = (location.x - self.location.x)/frames 
 
\t \t deltaY = (location.y - self.location.y)/frames 
 
\t \t counter = 0 
 
\t \t setInterval(function() { 
 
\t \t \t self.location.x += deltaX 
 
\t \t \t self.location.y += deltaY 
 
\t \t \t counter++ 
 
\t \t \t self.draw() 
 
\t \t \t if(counter >= frames) 
 
\t \t \t \t clearInterval() 
 
\t \t }, 1000/FPS) 
 
\t } 
 
\t self.image.onload = function() { 
 
\t \t Candy.list.push(self) 
 
\t \t Candy.queue.splice(0, 1) 
 
\t \t 
 
\t \t if(Candy.queue.length == 0) 
 
\t \t \t draw() 
 
\t \t else 
 
\t \t \t Candy(Candy.queue[0].img, Candy.queue[0].location, Candy.queue[0].canvas) 
 
\t } 
 
} 
 
Candy.list = [] 
 
Candy.queue = []

這裏就是我所說的功能糖果:

gameStarted = true 
 
\t Candy.queue.push({img: "client/img/candy.png", location: {x: width/3 - 87.5, y: height/10}, canvas: canvasContext}) 
 
\t Candy.queue.push({img: "client/img/candy2.png", location: {x: width/3 - 87.5, y: 3 * (height/10)}, canvas: canvasContext}) 
 
\t 
 
\t Candy(Candy.queue[0].img, Candy.queue[0].location, Candy.queue[0].canvas)

最後,這裏是繪製函數:

function draw() { 
 
\t colorRect(0, 0, canvas.width, canvas.height, 'white'); 
 
\t colorText("Player 1", 0.02, 0.05, "black", "40px Comic Sans"); 
 
\t colorText("Player 2", 0.88, 0.05, "black", "40px Comic Sans"); 
 
\t 
 
\t if(!gameStarted) { 
 
\t \t if(player1.ready) 
 
\t \t \t colorText("Ready", 0.02, 0.09, "green", "20px Comic Sans"); 
 
\t \t else 
 
\t \t \t colorText("Not Ready", 0.02, 0.09, "red", "20px Comic Sans"); 
 
\t \t if(player2.ready) 
 
\t \t \t colorText("Ready", 0.88, 0.09, "green", "20px Comic Sans"); 
 
\t \t else 
 
\t \t \t colorText("Not Ready", 0.88, 0.09, "red", "20px Comic Sans"); 
 
\t \t if(player1.ready && player2.ready) 
 
\t \t \t colorText("Press a button to start the game!", 0.32, 0.5, "black", "40px Comic Sans") 
 
\t }else{ 
 
\t \t alert(Candy.list[0].image.src) 
 
\t \t alert(Candy.list[0].getImg()) 
 
\t \t for(var i = 0; i < Candy.list.length; i++) { 
 
\t \t \t Candy.list[i].draw() 
 
\t \t } 
 
\t \t //TODO 
 
\t } 
 
}

+0

您應該考慮將'move'和'draw'從'self'屬性(而不是'this',因爲您已經找出問題所在)移動到'Candy.prototype'。這樣,所有'糖果'將分享參考,而不是擁有自己的這些功能副本。 –

回答

0

好吧,我想通了。在這個函數中,我用這個替換了自己,並且解決了這個問題。不需要任何回覆。

相關問題