Home > Software design >  Passing correct context with "this" to external method from class
Passing correct context with "this" to external method from class

Time:01-04

Let's say I have a very simple class that extends other classes, and an object of functions i'm passing to class B

const actions = {
   doSomething: (this: B, foo: boolean) => {
      console.log('from do something', this.text, foo);
   }
}
class B {
  actions = actions;
  text: string;
  constructor() {
    this.text = 'abc';
  }
}
class A extends B {
   runAction(foo) {
      this.actions.doSomething(false);
   }
}


const instance = new A();
instance.runAction(); // 'from do something, undefined, false'

ts compiler is also saying the this context isn't correct when calling from within runAction

Is there a better way to do this?

We have over 500 actions, and we want to provide access to the class data to every action and don't want to pass the arguments through all the actions.

CodePudding user response:

This

this.actions.doSomething(false);

calls the method with a this of this.actions. But this.actions is the plain object with the doSomething method - not the instance itself. You will need to use .call instead, as well as changing the doSomething arrow function to a regular function/method so it can capture a different this. The foo argument should be typed too (or removed).

Typing this inside runAction could be useful as well, though not always necessary.

const actions = {
   doSomething(this: B, foo: boolean) {
      console.log('from do something', this.text, foo);
   }
}
class A extends B {
   runAction(this: A) {
      this.actions.doSomething.call(this, false);
   }
}
  • Related