1
class Counter {
constructor(initialValue = 0) {
this.value = initialValue;
}
increment() {
this.value += 1;
}
}
const counter = new Counter();
console.log(counter.value); // 0
counter.increment();
console.log(counter.value); // 1
counter.value = 42; // <-- any way to forbid this?
counter.increment();
console.log(counter.value); // 43 :(
「可變的只有自己的方法」 是一樣的「私家到自己的方法,W ith公共獲得者「。適用相同的解決方案,方法和缺點。 – Bergi