无法编译为什么您无法识别操作员此错误

问题描述 投票:-1回答:1

下面的代码不能编译为什么您不能在容器类中标识运算符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)
    }
}
typescript
1个回答
2
投票

您遇到的第一个问题是您正在this内使用functionthis内部的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
© www.soinside.com 2019 - 2024. All rights reserved.