rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

How to assign the update the static member in a class in es6/js

This is a simple operation, but it seems to be tricky. so here is a simple class with a static method.

export class MyClass {
  static foo = {"key" : "value"};

  static bar = JSON.parse(JSON.stringify(MyClass.foo));
  MyClass.bar["key"] = "newVal";
}

considering that foo is a very large object that wants to copy in another static variable bar. after coping I want to update some properties.

but this doesn't seem to work, getting error, Unknown keyword or identifier. Did you mean 'class'?

MyClass.bar["key"] = "newVal"; this is invalid.

what's the issue here? how to update the static member just after assigning.

Upvotes: 0

Views: 89

Answers (1)

VLAZ
VLAZ

Reputation: 29037

You can use a static initialisation block:

class MyClass {
  static foo = {"key" : "value"};

  static bar = JSON.parse(JSON.stringify(MyClass.foo));
  static {
    MyClass.bar["key"] = "newVal";
  }
}
console.log(MyClass.foo);
console.log(MyClass.bar);

Or do the whole initialisation in the static block:

class MyClass {
  static foo = {"key" : "value"};

  static {
    //`this` in a static block refers to the class
    this.bar = JSON.parse(JSON.stringify(MyClass.foo));
    this.bar["key"] = "newVal";
  }
}
console.log(MyClass.foo);
console.log(MyClass.bar);

An alternative would be an immediately invoked function expression (IIFE) for environments that do not support static blocks:

class MyClass {
  static foo = {"key" : "value"};

  static bar = (() => {
    const obj = JSON.parse(JSON.stringify(MyClass.foo));
    obj["key"] = "newVal";
    return obj;
  })();
}
console.log(MyClass.foo);
console.log(MyClass.bar);

Or just put the update after the class declaration:

class MyClass {
  static foo = {"key" : "value"};
  static bar = JSON.parse(JSON.stringify(MyClass.foo));
}
MyClass.bar["key"] = "newVal";
console.log(MyClass.foo);
console.log(MyClass.bar);

Upvotes: 3

Related Questions