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?
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;
}
}