有没有办法只通过类方法使类字段可变?

时间:2017-06-01 09:40:00

标签: javascript oop ecmascript-6 encapsulation es6-class

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 :(

1 个答案:

答案 0 :(得分:0)

我不知道有什么方法可以在实例上获得值,但只有在类实例函数体外部访问时才禁止写访问。如果您只想在类实例方法(get和set)中访问,可以查看私有字段:github.com/tc39/proposal-private-fields

您还可以使用gettersWeakMaps来处理这些限制:

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 :)