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

202
Views
How to pass callback to init function in a class

As I mentioned in the title, I would like to pass some function as a callback to init function in some class

I will put here some basic structure:

class Person {

  constructor() {
    this.nums = [1, 2, 3];
    this.init();
  }
  init() {
    this.nums.forEach(num => {
      console.log(num);
    });
  }
}

Let's say I would like to add this function as a callback to the init function:

function test() {
  console.log('test')
}

How can i do this

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

0

class Person {
  constructor(cb) {
    this.nums = [1, 2, 3];
    this.cb = cb;
    this.init()
  }
  init() {
    this.nums.forEach(num => {
      console.log(num)
    })
    this.cb()
  }
}

const test = () => {
  console.log('test')
}

const myPerson = new Person(test)

about 4 years ago · Juan Pablo Isaza Report

0

Declare callback as a parameter in your init method, & call the callback at the end of your init method.

While calling your init method, pass test as an argument.

about 4 years ago · Juan Pablo Isaza Report

0

In case the OP wants to have the callback invoked as if it was a method of the Person instance and in addition also wants to handle the passing of arguments to such a callback then init is not anymore just an initializer.

It turns into a single generic method of any Person instance which does invoke any passed function within such an instance' context while passing the rest of its arguments to the callback.

Such a method then might be renamed from init to execute ...

function pushNumberValues(...values) {
  this.nums.push(...(values.flat()));
}
function logInstanceNumbers() {
  this.nums.forEach(num =>
    console.log(num)
  );
}

class Person {
  constructor() {  
    this.nums = [0, 1, 2];
  }
  execute(callback, ...args) {
    return callback.apply(this, args);
  }
}
const person = new Person;

person.execute(pushNumberValues, 3, 4, 5, 6);
person.execute(pushNumberValues, [7 , 8 , 9]);

person.execute(logInstanceNumbers);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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!