【问题标题】:typescript external callback binding within classes类中的打字稿外部回调绑定
【发布时间】:2021-12-23 21:57:01
【问题描述】:

我正在尝试将类的属性绑定到该类中的回调。

快速示例:

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(() => {
    console.log(this.member) // error TS2532: Object is possibly 'undefined'
  }
}

// TestClass
...
member: string = 'test';

second(cb: () => void) {
 const self = this;
 cb.bind(self)();
}

this 似乎可能未定义。

如何从外部回调访问类成员?

【问题讨论】:

    标签: javascript typescript callback binding


    【解决方案1】:

    Arrow Functions 用于自动绑定到当前作用域和父对象,因此您不能使用回调绑定来调用它们。 所以这里 javascript interpreter 试图找到之前定义了回调的父级。

    // caller
    const first = (): void => {
      const testClass = new TestClass();
      testClass.second(function() {
        console.log(this.member)
      }
    }
    

    【讨论】:

      【解决方案2】:

      在控制台日志前添加条件,避免打印未定义的对象。

      从你的例子:

      // caller
      const first = (): void => {
        const testClass = new TestClass();
        testClass.second(() => {
          if (this.member) console.log(this.member)
        }
      }
      
      // TestClass
      ...
      member: string = 'test';
      
      second(cb: () => void) {
         const self = this;
          cb.bind(self)();
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多