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

161
Vistas
Is there a way to set a singular value in a WeakMap in an extended class in JavaScript?

I'm not sure I've worded the question very clearly, though essentially I have two classes in this example code, a 'Car' class and a 'CustomCar' class.

I'm experimenting with WeakMaps for private class members, and I want to amend one of these WeakMap values in an extending class, my code is as shown:

const privateProperties = new WeakMap();

// Car Class
class Car {
  constructor(colour, seats) {
    privateProperties.set(this, {
      colour: colour,
      seats: seats,
      type: 'Car',
    });
  }

  get colour() {
    return privateProperties.get(this).colour;
  }

  start() {
    console.log(
      `Started the ${privateProperties.get(this).colour} ${
        privateProperties.get(this).type
      } with ${privateProperties.get(this).seats} seats!\n`
    );
  }
}

// Custom Car Class
class CustomCar extends Car {
  constructor(colour, seats, type = 'Custom Car') {
    super();
    privateProperties.set(this, {
      colour: colour,
      seats: seats,
      type: type,
    });
  }
}

module.exports.Car = Car;
module.exports.CustomCar = CustomCar;

I wanted to change the value associated with the 'type' key in the CustomCar class to whatever value is entered as a parameter i.e:

let myCar = new CustomCar('blue', 5, 'Polo');

In the above code, the 'type' value would be set to 'Polo'.

However, the only way I have been able to do this thus far is by duplication of code from the parent class:

privateProperties.set(this, {
      colour: colour,
      seats: seats,
      type: type,
    });

I can't seem to set the type value in the WeakMap any other way, is this code correct in terms of best practices?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You don't need to assign the entire privateProperties element, just replace the type property.

class CustomCar extends Car {
  constructor(colour, seats, type = 'Custom Car') {
    super(colour, seats);
    privateProperties.get(this).type = type;
  }
}
about 4 years ago · Santiago Trujillo 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