2017-06-01 28 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 :) 
相關問題