2016-04-07 11 views
-1

私は次のクラスを持っている:ゲッターが毎回異なる値を返すのはなぜですか?

class Counter { 

    constructor(start) { 
     this.start = start; 
    } 

    set start(number) { 
     this._start = number; 
    } 

    get start() { 
     return this._start++; 
    } 

    next() { 
     return this.start + 1; 
    } 
} 

次のように私はそれをインスタンス化:

let counter = new Counter(23); 

私は私の次の機能を実行する場合、それは正常に動作します:

counter.next(); // 24 
counter.next(); // 25 
// ... 

しかし、私はログアウトした場合start私はいつも違う何かを得る

counter.start; // 25; 
counter.start; // 26; 

なぜこのようなことが起こっていますか?

私は間違っていましたか?

+2

'this._start'または' this.start'? – isvforall

+1

私はこれが現実的な質問ではないと思います。ユーザーは、このような状況に直面することはまずありません。 –

+1

'this._start ++'は呼び出されるたびに 'this._start'をインクリメントします。あなたのコードはそれが想定していることをやっています。 'this._start'をインクリメントしたくない場合は、' ++ 'を使わないでください。 – jfriend00

答えて

3

はい問題があります。

Counterクラスは誤って意図的ではないゲッターのオブジェクトを突然変更しています。あなたが行うことができます修正するには

class Counter { 

    constructor(start) { 
     this.start = start; 
    } 

    set start(number) { 
     this._start = number; 
    } 

    get start() { // always return the current start 
     return this._start; 
    } 

    next() { // increase the start only in the next function! 
     return ++this.start; 
    } 
} 
関連する問題