Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Pass a function that uses other functions as parameter in Javascript

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!