0

Doing graphics in JS I found that I need to use windows.requestAnimationFrame and to be able to access 'this' I need to bind my drawing function to 'this'.

requestAnimationFrame(this.MyDrawFunction.bind(this));

But later I found another example, where I can just pass a delegate

window.requestAnimationFrame(() => this.MyDrawFunction());

Could you please help me understand, what is the differences between those 2? I understand the 2nd call my function in (with?) a proper closure. How does the 1st function principally different? Which variant should I use?

Thanks!

P.S. I have my code as a part of the Angular 10 application if it makes any difference.

Drenai
  • 7,125
  • 5
  • 40
  • 67
Budda
  • 16,990
  • 33
  • 113
  • 197
  • Use neither of these. In both cases you are creating a new function at every frame, which will make the memory garbage grow over time inevitabily asking the collector to kick in at random and eating precious time needed by tour animation, and propbably even making your animation miss frames resulting in hiccups. Instead create once the context unaware function (no matter which form you chose) and always reuse that one function. – Kaiido May 02 '21 at 23:50

1 Answers1

0

MyDrawFunction cares about it's internal value this

The value of this depends on how it is called.

If you pass MyDrawFunction to requestAnimationFrame then requestAnimationFrame will call it in the context of the window object. That is not the value of this that you need.

To deal with this you have to create a new function which will call MyDrawFunction with the right value of this.

The bind method creates a new function which calls it with the first argument as the this value.

Your arrow function calls it on the this object (which makes that its value of this). Note that arrow functions have a lexical this and not a this determined by how it was called, so requestAnimationFrame doesn't make it window.)

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205