Home > Back-end >  typescript external callback binding within classes
typescript external callback binding within classes

Time:11-11

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.

How can I access the classes members from an outside callback?

CodePudding user response:

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

CodePudding user response:

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. so here javascript interpreter is trying to find the parent which the callback has been defined before.

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