2017-08-29 29 views
1

我有一個將傳遞給requestAnimationFrame的方法的對象。 目前我創建的對象,而不是使用箭頭函數重新分配方法,它返回。使用箭頭函數作爲傳遞給requestAnimationFrame的方法

var player={fn:function(){return()=>{game.circle(this.x,this.y,this.radius)}}, 
x:200,y:300,radius:20}; 
player.fn=player.fn(); 

這樣做可以在創建對象後不重新分配方法嗎?

回答

2

你可以只use a static reference to player instead

const player = { 
    fn() { 
    game.circle(player.x, player.y, player.radius); 
    }, 
    x:200, 
    y:300, 
    radius:20 
}; 
requestAnimationFrame(player.fn); 

但是,沒有,否則就沒有辦法寫,而不需要單獨分配。通常你會然而剛剛bind or use the arrow function打電話時​​:

var player = { 
    fn() { 
    game.circle(this.x, this.y, this.radius); 
    }, 
    x:200, 
    y:300, 
    radius:20 
}; 
requestAnimationFrame(() => player.fn()); 
+0

雖然你的答案會工作,我路過的方法來請求動畫幀的方式,這是行不通的。然而你的鏈接綁定應該正常工作謝謝 – user7951676

+0

@ user7951676那麼你沒有在問題中顯示你的代碼的一部分,所以我不能建議它 – Bergi

+0

這很好,我明白,謝謝你 – user7951676

相關問題