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