Home > Enterprise >  TypeScript: Accessing a member from a function passing as a function object
TypeScript: Accessing a member from a function passing as a function object

Time:12-12

I am trying to write a basic generic code where I want to pass a function as a parameter to another function. The problem is: when I am passing the function as a parameter, I do not know the arguments. The arguments will be calculated before the actual call of the method.

Sample code:

import { Component, Input, OnInit } from '@angular/core';
@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent implements OnInit {
  @Input() name: string;
  private zopa = new Zopa();
  ngOnInit() {
    let addResult = this.methodCaller(this.add);
    console.log('Add Result: ', addResult);
    let subtractResult = this.methodCaller(this.subtract);
    console.log('Subtract Result: ', subtractResult);
  }
  methodCaller(method) {
    const x = 5;
    const y = 4;
    return method(x, y);
  }
  add(a, b) {
    console.log('add method calling ', this.zopa.prop);
    return a   b;
  }
  subtract(a, b) {
    console.log('subtract method calling... ');
    return a - b;
  }
}

class Zopa {
  prop = 'zopa';
}

Now it gives an error:

Error: Cannot read properties of undefined (reading 'zopa')

Basically in the methodCaller I just want to pass the function add as a function object. But the actual parameters 5, 4 can only be determined inside the methodCaller. I can not have it during the calling of methodCaller (at line:11, 13 inside ngOnInit() method).

So my question is: How can I access the this.zopa.prop inside the methods add and subtract in typescript?

CodePudding user response:

Your methods have incorrect this as you don't bind them in any way

class A {
  add(a: number, b: number) {
    console.log('this is', this, [a, b])
  }
  test() {
    this.add(1, 1);
    let f = this.add; // <- this is undefined
    f(2, 2);
    let g = this.add.bind(this);
    g(3, 3);
    let e = (a: number, b: number) => this.add(a, b);
    e(4, 4);
    let s = 'add' as const;
    let h = (a: number, b: number) => this[s](a, b);
    h(5, 5);  
  }
}

console.clear()
new A().test()
  • Related