Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda