Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda