下面的代码不能编译为什么您不能在容器类中标识运算符this。
class MyComponent {
public data: Array<Object>;
public someAttribute: string;
async constructor() {
let info = await this.getData('http://localhost:8080/api/users')
let check = function (data) {
this.someAttribute = data.someAttribute
}
check(info)
}
}
您遇到的第一个问题是您正在this
内使用function
。 this
内部的function
与您所期望的含义不同。您想改用arrow function:
let check = (data) => {
this.someAttribute = data.someAttribute
}
我看到的第二个问题是您已将constructor
标记为async
。你不能这样做。另外,由于您无法将async
设置为constructor
,因此,您无法在await
中设置getData
您的constructor
功能。正确的方法是创建某种init
函数,然后在此处进行async
调用。
查看此:async constructor functions in TypeScript?
最后但并非最不重要的是,您有this.getData
。您的getData
类上没有名为MyComponent
的函数。该行将失败。
this
的含义如何变化的示例:
class MyComponent {
constructor() {
this.someAttribute = 'test';
}
}
class MyComponent2 {
constructor() {
( function () {
console.log('IIF Test');
console.log('this', this); // undefined
this.someAttribute = 'test'
} ());
}
}
console.log(new MyComponent().someAttribute); // Test
console.log(new MyComponent2().someAttribute); // Exception