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

159
Views
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 answers
Answer question

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 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!