0

I'm trying to understand how binding works in Javascript and the following example works. But when I try to use this.numbers.map(this.doSomething) it gives me an error because doSomething is being statically called. To make it work again I'll have to use the second example, but I don't understand exactly what's happening. Anyone have some links / documentation I could use to understand this a bit better?

First example:

export class SomeClass{
  numbers = [1, 2, 3];
  showNumber = (value: number) => console.log(`number is:`, value);

  processNumbers = () => {
    const a = this.numbers.map(b => this.doSomething(b));

    // this gives me the error: 'showNumber' doesn't exist
    // const a = this.numbers.map(this.doSomething);

    // do something with a
  }

  private doSomething(value: number) {
    this.showNumber(value);
  }
}

const someClass = new SomeClass();
someClass.processNumbers();

Second example:

export class SomeClass{
  numbers = [1, 2, 3];
  showNumber = (value: number) => console.log(`number is:`, value);

  processNumbers = () => {
    const a = this.numbers.map(this.doSomething);

    // do something with a
  }

  private doSomething = (value: number) => {
    this.showNumber(value);
  }
}

const someClass = new SomeClass();
someClass.processNumbers();
Henny Lee
  • 2,808
  • 3
  • 17
  • 33
  • 2
    See the answers to the linked questions for details. I also wrote this up in an old post on my previous anemic blog: [*You must remember `this`*](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html). – T.J. Crowder Oct 22 '21 at 09:52

0 Answers0