我不確定我是否非常清楚地表達了這個問題,盡管在這個示例代碼中基本上我有兩個類,一個“Car”類和一個“CustomCar”類。
我正在為私有類成員試驗 WeakMaps,我想在擴展類中修改這些 WeakMap 值之一,我的代碼如下所示:
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;
我想將與 CustomCar 類中的“型別”鍵關聯的值更改為作為引數輸入的任何值,即:
let myCar = new CustomCar('blue', 5, 'Polo');
在上面的代碼中,“type”值將設定為“Polo”。
但是,到目前為止,我能夠做到這一點的唯一方法是從父類復制代碼:
privateProperties.set(this, {
colour: colour,
seats: seats,
type: type,
});
我似乎無法以任何其他方式在 WeakMap 中設定型別值,就最佳實踐而言,這段代碼是否正確?
uj5u.com熱心網友回復:
您不需要分配整個privateProperties元素,只需替換type屬性。
class CustomCar extends Car {
constructor(colour, seats, type = 'Custom Car') {
super(colour, seats);
privateProperties.get(this).type = type;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461600.html
標籤:javascript
上一篇:使用多種型別的打字稿問題
