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?