2016-08-19 54 views
0

我試圖遞歸調用一個函數,直到遊戲結束,但是,在執行過程中「this」被重置爲'window',這導致了以下錯誤:「can not read property未定義的'步驟'。「Javascript綁定問題沒有通過調用綁定解決

我試圖重寫違規行

this.game.bind(this).step(); 

以及

this.game.step.bind(this); 

無論是在工作。對於上下文來說,step只是一個調用Game中兩個助手的函數,用於移動對象並查找碰撞,當我使用這些而不是step時,錯誤依然存在。

/* globals key */ 
const Game = require('./game.js'); 
let speed = 1; 


function GameView(ctx) { 
    this.ctx = ctx; 
    this.game = new Game(); 
} 

GameView.prototype.start = function (callback) { 
    // let that = this 
    this.bindKeyHandlers(); 
    this.animate(0); 
}; 

GameView.prototype.animate = function(time) { 

    speed += 1; 
    if (speed >= 605) { 
     speed = 0; 
    }; 

    this.game.step(); 
    this.game.draw(this.ctx, speed); 
    if(!this.game.lose()){ 
     requestAnimationFrame(this.animate()); 
    } 
    else { 
    this.ctx.fillStyle = "white"; 
    this.ctx.font = "italic "+24+"pt Arial "; 
    this.ctx.fillText(`Game Over \n Press Enter to restart`, 100,200); 
     key('enter',()=>{ 
     this.game = new Game(); 
     this.start(); 
     }); 
    } 
}; 


GameView.prototype.bindKeyHandlers = function() { 
    key('d',() => { 
    this.game.ship.power([2, 0]); 
    }); 
    key('a',() => { 
    this.game.ship.power([-2, 0]); 
    }); 
    key('s',() => { 
    this.game.ship.power([0, 2]); 
    }); 
    key('w',() => { 
    this.game.ship.power([0, -2]); 
    }); 
    key('l',() => { 
    this.game.ship.fireBullet(); 
    }); 
}; 


module.exports = GameView; 
+0

'javascript'使用'.bind()'在哪裏?傳遞給'requestAnimationFrame'的參數應該是對函數的引用嗎? – guest271314

+0

你確定'new Game()'產生一個對象嗎? – Mike

+0

你知道'.bind()'返回一個新函數,然後你需要調用嗎?你試過的例子都沒有調用'.bind()'返回的函數。 – jfriend00

回答

0

你的問題是,animate功能this並不是指你希望它的上下文。所以你的違規路線(或缺乏)完全在別處。

Function.bind返回一個函數,你需要這個新的綁定函數的地方,這是構造函數的完美位置。這裏有一個例子:

function GameView(ctx) { 
    this.ctx = ctx; 
    this.game = new Game(); 
    this.animate = this.animate.bind(this) 
} 

請參閱本jsfiddle更多,請記住從呼叫notBound

希望這有助於打開你的開發者控制檯,見證了錯誤!