Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!