Home > front end >  Keep current class context while calling dynamic function
Keep current class context while calling dynamic function

Time:10-25

When I launch this script I get

Cannot read private member from an object whose class did not declare it

How can I call helloService from a dynamicaly called function (sendToto) without manually injecting it?

export class HelloService {
  sayHello(name: string) {
    console.log('hello', name)
  }
}
export class myClass {
  readonly #helloService: HelloService;

  names: { [index: string]: Array<Function> } = {
    toto: [this.sendToto]
  }

  constructor() {
    this.#helloService = new HelloService();
  }

  send(name: string) {
    // @ts-ignore
    this.names[name][0]('someparams')
    }
  sendToto(params: string) {
    //Cannot read private member from an object whose class did not declare it
    this.#helloService.sayHello(params)
  }
}
(new myClass()).send('toto');

CodePudding user response:

Method 1:

Replace toto: [this.sendToto] with toto: [this.sendToto.bind(this)]

Method 2:

Make sendToto an arrow function, but has to be declared before names

  sendToto = (params: string) => {
    //Cannot read private member from an object whose class did not declare it
    this.#helloService.sayHello(params)
  }
  
  names: { [index: string]: Array<Function> } = {
    toto: [this.sendToto]
  }
  • Related