Reputation: 28
I have a class that constructs objects. Can I run a method in all the object instances without knowing the names of the objects themselves?
class Person{
constructor (_a){
this.a = _a;
}
sayfood(){
console.log(this.a);
}
}
let person1 = new Person("cheese");
let person2 = new Person("milk");
My current best solution is to loop through the instances like this:
for (var i = 1; i < 3; i++) {
eval("person" + i).sayfood();
}
It works, but I imagine there is a better way. I have tried placing the new object instances as elements of an array, and then iterating through them using foreach, but I could not get that working.
Upvotes: 0
Views: 147
Reputation: 816
I have tried placing the new object instances as elements of an array, and then iterating through them using foreach, but I could not get that working.
That would indeed be a better way. This is how you would use forEach
to achieve that:
class Person{
constructor (_a){
this.a = _a;
}
sayFood(){
console.log(this.a);
}
}
const person1 = new Person("cheese");
const person2 = new Person("milk");
const persons = [person1, person2]
persons.forEach(person => person.sayFood())
Upvotes: 1