Reputation: 748
Let's say I have a Class with a method like:
class MyClass {
importantMethod() {
... //any code here
}
}
And let's say I have 10/20/more instances of the Class like:
const inst1 = new MyClass();
const inst2 = new MyClass();
const inst3 = new MyClass();
.... //and more instances here
Is there a way to execute importantMethod()
on each instance in a more elegant way than:
inst1.importantMethod()
inst2.importantMethod()
inst3.importantMethod()
.... //and for all the instances
Upvotes: 1
Views: 785
Reputation: 115940
I assume you want to be able to run a function (at any time, and possibly many times) on all instances of a class that happen to exist at any given moment. YOu could do this by simulating a "private static" list of instances of the class. Each instance gets added to the list on the class's constructor
call, and you can supply a function that will iterate over this list:
let MyClass;
{
// this is only visible to functions inside the block
let myClassInstances = [];
MyClass = class {
constructor() {
myClassInstances.push(this);
}
importantMethod() {
console.log(this);
}
}
MyClass.runImportantMethodOnAll = function() {
myClassInstances.forEach(inst=>inst.importantMethod());
}
};
You could use this like:
let x = new MyClass();
let y = new MyClass();
MyClass.runImportantMethodOnAll();
There is no need to attach the runImportantMethodOnAll
to MyClass
, either. You could store it anywhere.
Upvotes: 1
Reputation: 7676
Use forEach
[inst1 , inst2 , inst3].forEach( (item)=> item.importantMethod() )
Upvotes: 2
Reputation: 808
I think that you have 2 options:
If this can be run on initialization and throws no errors etc and is safe you can run it in the constructor and thus every time there is a new instance it will call it... Not the best practice but possible....
Do something like
const instances = [];
for (let i=0; i<20; i++) {
const classInstance = new MyClass();
classInstance.ImportantFunction();
instance.push(classInstance);
}
This is also sort of a hack but it might make the code a bit cleaner if you have a lot of instances...
If you care about naming the instance then you can change the array in example above to an object and actually put every instance with a named key in the object and then it would be easier to access the instances.
That's from my knowledge at least, I'm not familiar with any "hooks" on class instantiation unfortunately.
Upvotes: 1