skip to Main Content

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


  1. For a one liner where you manually list the instances:

    [inst1, inst2, inst3, inst4].forEach(el => {el.property = true;})
    

    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.

    Login or Signup to reply.
  2. 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:

    class InstanceCollection{
      static instances = [];
      static updateProperties(props){
        const instances = InstanceCollection.instances;
        for(const prop in props){
          for(let i = 0; i < instances.length; i++){
            const instance = instances[i].deref();
            instance ? (instance[prop] = props[prop]) : instances.splice(i--, 1);
          }
        }
      }
      static addInstance(instance){
        InstanceCollection.instances.push(new WeakRef(instance));
      }
    }
    
    
    class MyClass extends InstanceCollection{
      constructor() {
        super();
        this.property = null;
        MyClass.addInstance(this);
      }
    }
    
    let inst1 = new MyClass(), inst2 = new MyClass(), inst3 = new MyClass(), inst4 = new MyClass();
    
    MyClass.updateProperties({property: true});
    
    console.log(inst1, inst2, inst3, inst4);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search