TypeScript - 如何在异步方法中访问 "this"?

4

我有这段代码:

export class Profile {

    private resource: Resource = new Resource();


    /**
     * Problem here
     */
    async initialize(): Promise<void> {
        console.log(this.resource);

        var html = await this.resource.fetch(true);

        const $profile = jQuery(html);

        console.log($profile.find("span.largetext"));


    }
}

如果你能看到这行代码 console.log(this.resource),我得到了undefined。异步方法无法访问“this”吗?
我还使用了console.log(this)来测试,它在web检查器中返回Profile { }
有没有办法可以访问this

“this”关键字所指向的对象取决于方法被调用的方式。 - Felix Kling
@FelixKling 这会改变什么呢? - Felix Lebel
嗯,就是this的值。但我刚才意识到你说它会引用一个Profile实例。在这种情况下,由于某种原因,this没有resource属性。 - Felix Kling
1个回答

3
class Profile {

    private resource: number = 1;


    /**
     * Problem here
     */
    async initialize(): Promise<void> {
        console.log(this.resource);
    }
}


let p = new Profile();
p.initialize();


let p = new Profile();
p.initialize();

我创建了一个样例脚本,它可以转换为:
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
    return new Promise(function (resolve, reject) {
        generator = generator.call(thisArg, _arguments);
        function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
        function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
        function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
        function step(verb, value) {
            var result = generator[verb](value);
            result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
        }
        step("next", void 0);
    });
};
class Profile {
    constructor() {
        this.resource = 1;
    }
    /**
     * Problem here
     */
    initialize() {
        return __awaiter(this, void 0, Promise, function* () {
            console.log(this.resource);
        });
    }
}
let p = new Profile();
p.initialize();
//# sourceMappingURL=main.js.map

输出结果为:
1

正如预料的那样。因此,结论是这不是关于this关键字,而是关于Resource类,我猜。


嗨@MartyIX,在es2017中,我能够在async方法内访问console.log(this),并且它也在控制台中显示,但是在调试期间,当我手动在控制台中输入“this”时,它显示为未定义。对于这个问题有什么建议或解决方案吗? - anirudh talluri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接