user7838288
user7838288

Reputation:

How to call multiple function calls at once

Is there a way to call a function from all of class instances at once?

function updateEverything() {
  // call update function of all of the Example instances
}

class Example {
  constructor() {
    this.data = { /* ... */ }
  }

  update() {
    // do something with this.data
  }
}

I tried to come up with a way of using callbacks but that flew over my head and I didn't find any other solution.

Upvotes: 0

Views: 204

Answers (1)

Alberto
Alberto

Reputation: 12919

If you are storing the variables in a array, the you just need:

array.forEach(el => el.update())

Otherwise you can use a sort of static property to store all the variables that you have instantiated:

class Example {
  constructor() {
    if(!Example.instances)
      Example.instances = [];
    Example.instances.push(this);
    this.data = {a: 1}
  }

  update() {
    console.log('update is called');
  }
  static updateAll(){
    if(Example.instances)
      Example.instances.forEach(el => el.update());
  }
}
const arr = [
  new Example(), // <-- doesn't need to be in a array
  new Example(), // <-- doesn't need to be in a array
  new Example(), // <-- doesn't need to be in a array
]
Example.updateAll();

Upvotes: 1

Related Questions