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 :(
答案 0 :(得分:0)
我不知道有什么方法可以在实例上获得值,但只有在类实例函数体外部访问时才禁止写访问。如果您只想在类实例方法(get和set)中访问,可以查看私有字段:github.com/tc39/proposal-private-fields
您还可以使用getters和WeakMaps来处理这些限制:
counter.js:
const privateProps = new WeakMap();
const get = instance => privateProps.get(instance);
const set = (instance, data) => privateProps.set(instance, data);
export default class Counter {
constructor(initialValue = 0) {
set(this, { value: initialValue });
}
increment() {
get(this).value += 1;
}
get value() {
return get(this).value;
}
}
main.js
import Counter from 'counter.js';
const counter = new Counter();
console.log(counter.value); // 0
counter.increment();
console.log(counter.value); // 1
counter.value = 42; // <-- don't define a getter to forbid this
counter.increment();
console.log(counter.value); // 2 :)