2017-06-01 27 views
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 :(

+0

“可变的只有自己的方法” 是一样的“私家到自己的方法,W ith公共获得者“。适用相同的解决方案,方法和缺点。 – Bergi

回答

0

我不知道的任何方式对实例的值,但只有当一个类的实例函数体的外部访问禁止写访问。你可以看一下私有字段,如果只想类的实例方法中访问(get和set):

counter.js:github.com/tc39/proposal-private-fields

你也可以使用gettersWeakMaps解决这些限制:

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 :) 
相关问题