0

Using Typescript 3.8.3 and node v12.16.2:

class dummy{
    public data = '12345';

    public somePromise(d : dummy){
        var e : dummy = this;
        return new Promise(function(resolve, reject) {
            console.log(d.data); //This is fine.
            console.log(e.data); //This is fine too.

            //However this, pun intended, is not fine:
            console.log(this.data); //TypeError: Cannot read property 'data' of undefined
            resolve ('promise');
        })
    }

    public async run(){
        console.log(this.data); //This is off course fine.
        await this.somePromise(this);
    }
}

var d = new dummy();
d.run();

Can someone please point me to some documentation that explains what is going on and why? Second question is how can I make visual studio code or the tsc compiler flag the error?

The answer is good. For details read here. And to make Visual studio flag the error use --noImplicitThis in tsconfig.json.

Robert Altena
  • 787
  • 2
  • 11
  • 26
  • 1
    Some good reading on `this` [here](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback). Basically, it no longer exists in callbacks. It doesn't scope like other local variables do. – Alex Wayne May 11 '20 at 21:57

1 Answers1

2

You are out of scope. One quick way would be to use the fat arrow notation e.g.

return new Promise((resolve, reject) => {
            resolve('promise');
        })
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • Thank you, definitely worth an up-vote! But now I have to wonder: Why are d and e in scope? – Robert Altena May 11 '20 at 21:56
  • 2
    Because `this` is a keyword that refers to the execution context, not a local variable. When another function is executed (your promise callback) the execution context changes. The arrow function `() => {}` does not change the context, however, and keeps `this` the same. – Alex Wayne May 11 '20 at 21:58