简体   繁体   English

类中的打字稿外部回调绑定

[英]typescript external callback binding within classes

I'm trying to bind properties of a class to a callback inside that class.我正在尝试将类的属性绑定到该类中的回调。

Quick example:快速示例:

// 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 seems to be possibly undefined. this似乎可能是未定义的。

How can I access the classes members from an outside callback?如何从外部回调访问类成员?

Add a condition before the console log to avoid print undefined objects.在控制台日志之前添加条件以避免打印未定义的对象。

from your example:从你的例子:

// 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)();
}

The Arrow Functions are for automatic binding to the current scope and parent objects, so you can't call them with bindings of your callbacks. Arrow Functions用于自动绑定到当前作用域和父对象,因此您不能使用回调的绑定来调用它们。 so here javascript interpreter is trying to find the parent which the callback has been defined before.所以这里 javascript interpreter器试图找到之前定义过回调的父级。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM