0

Considering the below, it looks like the call with implicit parameter is like a static call, the initialized property becomes undefined.

Is this expected? If yes, why?

export class MyClass {
  private prop: string;
  constructor(){
    this.prop = 'value!';
  }
  foo(){
    // This works
    something.subscribe((x: string) => this.bar(x));

    // This doesn't
    something.subscribe(this.bar);
    //...
  }
  bar(z: string) {
    console.info(this.prop);
    // Is undefined with second call
  }
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
Harps
  • 640
  • 8
  • 17
  • As @CRice mentioned, the scope changes if the method is not called within an arrow function or using *bind* (`something.subscribe(this.bar.bind(this));`). – naeramarth7 Oct 05 '18 at 20:02
  • Since the linked question is for vanilla js only, I'll add that since you're using typescript you have some additional options not listed there, such as using a [`@bind` decorator](https://www.npmjs.com/package/bind-decorator) on `bar` when you declare it. – CRice Oct 05 '18 at 20:04
  • Why @bind when you could just use arrow function on a property? e.g. "bind = ()=>{}". Since its an arrow f. TypeScript then bind's it to current scope (that is the class in this case). – Per Svensson Oct 05 '18 at 20:15
  • Cleanest syntax is the .bind(this) I think. This looks like something that could be fixed in the language (I mean js) at some point. If one want another context than the current instance, he would use a static function instead. Thanks for answering guys, it is crystal clear now! – Harps Oct 05 '18 at 20:34

0 Answers0