gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:31:02 24 4
gpt4 key购买 nike

我有这段代码:

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) 这行,我得到了未定义。异步方法不能访问“this”吗?

我还使用 console.log(this) 进行了测试,它在网络检查器中返回了 Profile { }

有什么方法可以访问 this 吗?

最佳答案

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 类。

关于TypeScript - 如何在异步方法中访问 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35264469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com