【问题标题】:Is there any way to make class fields mutable only by class methods? [duplicate]有什么方法可以使类字段仅通过类方法可变? [复制]
【发布时间】:2017-11-02 09:24:10
【问题描述】:

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

【问题讨论】:

  • “仅由自己的方法可变”与“私有到自己的方法,具有公共 getter”相同。相同的解决方案、方法和缺点也适用。

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


【解决方案1】:

我不知道有任何方法可以在实例上获取值,但只有在类实例函数体之外访问时才禁止写访问。如果您只想在类实例方法(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 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-15
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多