user22588911
user22588911

Reputation:

Is it possible to modify properties of multiple objects or class instances all at once with one line of code?

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.

Upvotes: 0

Views: 337

Answers (3)

Make the property static. And change it globaly for the class.

class MyClass {
  static prop = null
  ...

  constructor() {
    ...
  }

  ...
}

MyClass.prop = 'some value'

Upvotes: -1

Alexander Nenashev
Alexander Nenashev

Reputation: 23309

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);

Upvotes: 0

jfriend00
jfriend00

Reputation: 707786

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.

Upvotes: 0

Related Questions