In JavaScript (assuming version is >= ES6), say that I have a class;
class MyClass {
constructor() {
this.property = null;
}
}
… and I create two new instances of the class;
let inst1 = new MyClass(), inst2 = new MyClass();
Now, say I want inst1
and inst2
‘s property
value to true
. This can be easily accomplished with
inst1.property = true;
inst2.property = true;
However, if I end up with many instances, reassigning each and every value, a new line each time, the code can get out of hand;
inst1.property = true;
inst2.property = true;
inst3.property = true;
inst4.property = true;
// ...
Now, I know, this is a very bad example, but you can just imagine a better example in its place. I wanted to know if there was any way to modify multiple instances with only one line of code, through something similar to object destructuring. For example,
[inst1, inst2, inst3, inst4].property = true;
I apologize if this is a bad question, but I just noticed my code getting messy with a scenario similar to this, and wondered if there was a solution to it. Thank you for your help.
2
Answers
For a one liner where you manually list the instances:
But, if you really want all instances to have the same value for that propery, then perhaps it shouldn’t be an instance variable and could just be a static property (a property on the class) that every instance can refer to.
Create a class with static methods that would collect a class’ instances’ weak references and update their props, than you can reuse it with any of your classes: