Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda