0

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?

1
  • ObjectB.myFunction didnt you declare it private ? Have you tried changing scope to public Commented Mar 30, 2022 at 1:57

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your quick response! The typo was my mistake while writing the question. The .bind was all I needed. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.