2014-04-14 22 views
0

我正在使用Javascript編寫Pong的版本。我有一個Game對象,我使用prototype屬性來定義它的方法。我收到以下錯誤:「未定義不是函數」。它在Game.prototype.step函數中被拋出,所以this.update在那裏沒有定義。這裏是遊戲對象的代碼:無法在JavaScript對象上引用方法

(function(root) { 
    var Pong = root.Pong = (root.Pong || {}); 

    var Game = Pong.Game = function() { 
    this.canvas = document.getElementById('canvas'); 
    this.canvas.width = 800; 
    this.canvas.height = 400; 
    this.context = canvas.getContext('2d'); 
    this.maxStartSpeed = 10; 
    this.keysDown = {}; 
    this.player2 = new Pong.Player({'player': 2}); 
    this.player1 = new Pong.Player({'player': 1}); 
    this.ball = new Pong.Ball(400, 200); 
    } 

    Game.prototype.update = function() { 
    this.player1.update(); 
    this.player2.update(); 
    this.ball.update(player1.paddle, player2.paddle); 
    }; 

    Game.prototype.render = function() { 
    this.context.fillStyle = "#bdc3c7"; 
    this.context.fillRect(0, 0, width, height); 
    this.player1.render(); 
    this.player2.render(); 
    this.ball.render(); 
    }; 


    Game.prototype.animate = function(callback) { 
    window.setTimeout(callback, 1000/60) 
    }; 

    Game.prototype.step = function() { 
    this.update(); 
    this.animate(this.step); 
    }; 

    window.addEventListener("keydown", function (event) { 
    Game.keysDown[event.keyCode] = true; 
    }); 

    window.addEventListener("keyup", function (event) { 
    delete Game.keysDown[event.keyCode]; 
    }); 

    window.onload = function() { 
    document.getElementById('canvas-container').appendChild(canvas); 
    game = new Game(); 
    game.animate(game.step); 
    }; 

})(this); 
+0

'window.setTimeout(callback,1000/60)'將'callback'的上下文更改爲'window'。 'window.update'沒有定義。 –

+0

[將正確的「this」上下文傳遞給setTimeout回調?](http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback) –

回答

1

setTimeout將改變範圍。要保持適當的範圍,則需要

this.animate(this.step); 

this.animate(this.step.bind(this)); 

你需要做同樣的事情,與其他有生命的呼叫使用bind

變化。

相關問題