awmleer
awmleer

Reputation: 1800

TypeScript 'this' scoping issue

My code:

export class WordService {
    constructor(private http:Http, private storage:Storage){}
    impulseData={
        get():Promise<any>{
            return this.storage.get('impulseData');
        }
    };
}

When I call myWordService.impulseData.get(), I found this.storage is undefined. So how can I reach the property storage inimpulseData.get?

I guess this problem was caused by the scoping of this. Maybe I should let the this inside and outside impulseData share the same scope?

Update:

Thanks to Suren Srapyan's answer, I finally change my code to this:

impulseData={
    get:()=>{
        return this.storage.get('impulseData');
    }
};

Upvotes: 1

Views: 594

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68635

this refers to the get() function's context which doesn't have storage property.

You can use arrow functions

export class WordService {
    constructor(private http:Http, private storage:Storage){}
    impulseData = {
        get: (): Promise<any> => {
            return this.storage.get('impulseData');
        }
    };
}

Or Try to get the this outside and create the object in the constructor. Also in this case you need to attach your object to this, because now it is scoped in the constructor and is not visible outside it, if it is not attached to this.

export class WordService {
    impulseData;

    constructor(private http: Http, private storage: Storage) {
        const context = this;
        this.impulseData = {
            get(): Promise<any> {
                return context.storage.get('impulseData');
            }
        };
    }
}

Or you can use only storage.get('impulseData'), if you create in the constructor

Upvotes: 4

hansmaad
hansmaad

Reputation: 18905

In this case you could use the constructor parameter without this.

constructor(private http:Http, private storage:Storage){
  impulseData = {
    get():Promise<any>{
        return storage.get('impulseData');
    }
  };

Otherwise you should use a local variable

constructor(private http:Http, private storage:Storage){
  let self = this;
  impulseData={
    get():Promise<any>{
        return self.storage.get('impulseData');
    }
  };

Upvotes: 0

Related Questions