打字稿“这个"范围问题 [英] TypeScript 'this' scoping issue

查看:34
本文介绍了打字稿“这个"范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

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

当我调用 myWordService.impulseData.get() 时,我发现 this.storageundefined.那么我怎样才能到达impulseData.get中的storage属性?

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

我猜这个问题是由this的范围引起的.也许我应该让 this 内外的 impulseData 共享相同的范围?

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?

更新:

感谢 Suren Srapyan 的回答,我终于将代码更改为:

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

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

推荐答案

this 指的是 get() 函数的上下文,它没有 storage 属性.

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

你可以使用箭头函数

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

或者尝试将 this 取出并在构造函数中创建对象.同样在这种情况下,您需要将您的对象附加到 this,因为现在它在构造函数中处于范围内并且在构造函数之外不可见,如果它没有附加到 this.

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');
            }
        };
    }
}

或者你可以只使用storage.get('impulseData'),如果你在构造函数中创建

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

这篇关于打字稿“这个"范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆