1

I have an object with a method that will be passed to requestAnimationFrame. At the moment I create the object than reassign the method with an arrow function it returns.

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

Can this be done without the reassigning the method after creating the object?

user7951676
  • 377
  • 2
  • 10

1 Answers1

2

You could just 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);

But no, otherwise there's no way to write this without a separate assignment. Usually you however would just bind or use the arrow function when calling requestAnimationFrame:

var player = {
  fn() {
    game.circle(this.x, this.y, this.radius);
  },
  x:200,
  y:300,
  radius:20
};
requestAnimationFrame(() => player.fn());
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Although your answer would work I'm passing the method to request animation frame in a way that it wouldn't work however your link to bind should work fine thank you – user7951676 Aug 29 '17 at 05:34
  • @user7951676 Well you haven't shown that part of your code in the question, so I can't advise on it – Bergi Aug 29 '17 at 05:39