Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda