0

In vanilla js, this would be the same (not sure anyway..).

The first one :

class MyClass {
    myData: Mydata;

    ngOnInit(): void {
        this.anyService.getAll().then(this.anyMethod)
    }
    anyMethod(data: MyData) {
      this.myData = data;
    }
 }

and the compiled js (part with this call is included)

this.anyService.getAll().then(this.anyMethod);

the call to any method will return an error, but with the second error:

class MyClass {
    myData: Mydata;

    ngOnInit(): void {
        this.anyService.getAll().then(data => this.anyMethod(data))
    }
    anyMethod(data: MyData) {
      this.myData = data;
    }
}

and the compiled js:

var _this = this;
this.anyService.getAll().then(function () { return _this.anyMethod(); });

the conversion

Ulysse BN
  • 6,678
  • 2
  • 37
  • 63
  • What is the problem? This question is not at all clear. – Pointy Dec 05 '16 at 02:32
  • 1
    In the first code, `this` in `anyMethod` will not be the `this` you think `this` is - assuming I understand the code and ngOnInit and anyMethod are properties of the same object – Jaromanda X Dec 05 '16 at 02:38
  • This is an extremely common question which has been answered many times, including [here](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). Your question title is misleading because it omits the `this` part which is crucial to this issue. –  Dec 05 '16 at 02:53
  • @JaromandaX yes they are method of the same object, but both `this` in callback aren’t the same ? Because I didn’t scope any one of them in a function. – Ulysse BN Dec 05 '16 at 09:33
  • no, you didn't, so `this` is clearly not the `this` you think `this` is - because you think it's `this` when in fact it's something else – Jaromanda X Dec 05 '16 at 09:34
  • @JaromandaX I added compiled js to try to understand more the issue, those are different in vanilla js ? calling this in a function parameter get the parent scope. – Ulysse BN Dec 05 '16 at 09:53
  • @torazaburo, I couldn’t find an answer in the link you gave me, I don’t see where the error come from.. – Ulysse BN Dec 05 '16 at 09:53
  • 1
    Here is a better dup, perhaps someone else can close against this: http://stackoverflow.com/questions/7890685/referencing-this-inside-setinterval-settimeout-within-object-prototype-methods –  Dec 05 '16 at 13:16
  • thanks @torazaburo i flagged this – Ulysse BN Dec 05 '16 at 18:18

0 Answers0