0

I started a new job and have limited experience with Javascript. I found a piece of code that really confuses me:

export default class Foo
{
  constructor()
  {
    this.bar = this.bar.bind(this); // the line that confuses me
  }

  bar(...) {...}
}

Is this line redundant? If not, what does it do?

Walker
  • 353
  • 1
  • 4
  • 10
  • It creates an instance version of `bar` that is prototype `bar` function but bound to `this`. Is it redundant? No way of telling from your snippet. – Xotic750 Sep 06 '19 at 14:09
  • 2
    It allows you to write something like `f = new Foo; b = f.bar; b(...)`. Without the binding, you would have to use `f.b(...)`. It also allows you to pass `f.bar` as a callback to another function, instead of `(...args) => f.bar(...args)` – Barmar Sep 06 '19 at 14:11
  • ".bind() simply creates a new function that, when called, has its this keyword set to the provided value. So, we pass our desired context into the .bind() function. Then, when the callback function is executed, this references the desired content(bar in this case)." https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/ This link explains how bind works with this keyword. Check it out. – Amrit Subedi Sep 06 '19 at 14:12
  • You may be seeing this in a React or Angular context. It makes it so that if you call `bar` from, say, an event handler (e.g. ` – Heretic Monkey Sep 06 '19 at 14:13
  • You often use that if you want to register `this.bar` as a callback for an event listener with bound `this`, and later, need to remove that event listener again. – t.niese Sep 06 '19 at 14:15
  • Unlike other OOP type languages were methods have a kind of simple struct `TMethod = { procedure, instance}`, in JS we don't have this. We have `TMethod = {procedure}`, IOW: we loose the instance. When using the dot notation the instance can be inferred. So `bind` can be used to kind of capture the `this` inside a closure. After doing this your method including the instance can be freely passed around. In simple terms a function that's using `bind` has both `instance` & `procedure`. You could say it's like creating a TMethod for those coming from C++/Delphi etc. – Keith Sep 06 '19 at 14:21

0 Answers0