0

What is the difference between this.function.bind(this) and this.function() in class declaration? For pure js

Rasul
  • 13
  • 3
  • 1
    [Similar to before?](https://stackoverflow.com/questions/57974389/what-is-the-use-of-this-function-bindthis) Although in this case `.bind()` just returns a new function, while `this.function()` will execute the function. – VLAZ Sep 17 '19 at 14:50
  • Possible duplicate of [Javascript call() & apply() vs bind()?](https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind) – Kate Orlova Sep 17 '19 at 14:58
  • I saw something like that document.addEventListener('keydown', this.onKeyPress.bind(this)). So it means if key is down then invoke the callback which is the function that is returned by .bind(), right? – Rasul Sep 17 '19 at 15:03
  • @Rasul yes. And that function will [use the correct context](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback). – VLAZ Sep 17 '19 at 15:05
  • It is clear now Thank you – Rasul Sep 17 '19 at 15:09

1 Answers1

0

In your samples, this keyword refers to different contexts.

this.function.bind(this) returns a new function, where this belongs to the execution context of the class. You may use arrow functions instead to get the same results without bind.

this.function() just calls the function, which gets its own context.

Vince
  • 149
  • 4
  • "*just calls the function, which gets its own context.*" unless it's already a bound function, the context would be the current `this` – VLAZ Sep 17 '19 at 15:01