Home > front end >  How to pass callback to init function in a class
How to pass callback to init function in a class

Time:09-23

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

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

:

How can i do this

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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; }

  • Related