I am developing a project in Typescript that has two classes like this:
class A{
//some attributes
function_to_pass(){
//Do something
this.someFunction();
//Make changes in object A
}
protected someFunction(){
//Do some stuff
}
}
class B{
private readonly _functionProvided: () => void;
constructor(functionProvided: () => void){
this._functionPassed = functionProvided;
}
private myFunction(){
//Do some stuff
this._functionProvided();
}
}
I want the object of class B to call the "function_to_pass" method in the object of class A, so i pass the function as a parameter in the constructor and then call "myFunction" in this object b. Like this
objectA = new A();
objectB = new B(objectA.function_to_pass)
objectB.myFunction()
But, i get the following error:
TypeError: this.someFunction is not a function
I suppose that objectB does not know about objectA, so objectB can't manipulate objectA.
Is there anyway i can do this?
CodePudding user response:
I see two problems with the code, the first I think is a typo: the class B
constructor doesn't initialize the instance data, _functionProvided
. (see FIX #1)
The second problem is the real problem, and has to do with the execution context of function_to_pass
. In order that this
be defined when it runs, the function must be bound to its instance. See (FIX #2).
class A{
//some attributes
function_to_pass(){
//Do something
this.someFunction();
//Make changes in object A
}
protected someFunction(){
//Do some stuff
}
}
class B{
private readonly _functionProvided: () => void;
constructor(functionProvided: () => void){
// FIX #1, no such thing as _functionPassed
// WAS: this._functionPassed = functionProvided;
this._functionProvided = functionProvided;
}
private myFunction(){
//Do some stuff
this._functionProvided();
}
}
let objectA = new A();
// FIX #2: bind the receiver of function_to_pass
// WAS: objectB = new B(objectA.function_to_pass)
let objectB = new B(objectA.function_to_pass.bind(objectA));
objectB.myFunction()