【问题标题】:not compile why you cannot identify the operator this error不编译为什么你不能识别运营商这个错误
【发布时间】:2020-03-06 16:07:35
【问题描述】:

以下代码部分无法编译为什么您无法识别容器类中的运算符 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.getData,但我在任何地方都没有看到它的定义...
  • 你不能有一个异步构造函数。
  • 这看起来根本不像 ES6 代码。你在用打字稿吗?

标签: typescript


【解决方案1】:

您遇到的第一个问题是您在function 内部使用thisfunction 内部的 this 与您所期望的含义不同。您想改用arrow function

let check = (data) => {
    this.someAttribute = data.someAttribute
}

我看到的第二个问题是您将constructor 标记为async。你不能这样做。此外,由于您不能 async 您的 constructor,这意味着您不能在您的 constructorawait 您的 getData 函数。正确的方法是创建某种init 函数并在那里调用async

看到这个:async constructor functions in TypeScript?

最后但并非最不重要的一点是,您拥有this.getData。您的 MyComponent 类上没有名为 getData 的函数。那条线会失败。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2018-12-02
    • 2014-01-02
    相关资源
    最近更新 更多