我有这段代码:
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)
行,我就得到了不确定。无法异步方法访问&#34;此&#34;?
我还使用console.log(this)
进行了测试,并在网络检查器中返回Profile { }
。
我有办法访问this
吗?
答案 0 :(得分: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
课程。