JavaScript classes with getter and setter cause RangeError: Maximum call stack size exceeded

前端 未结 5 458
南方客
南方客 2020-11-30 11:12

I am currently experimenting with ECMA6 classes. My current class looks like the following

class Player {
  constructor(id) {
    this.id = id;
    this.cash         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 11:34

    You are calling recursively your getter.

    It follows a possible alternative:

    class Player {
        constructor(id) {
            this.id = id;
            this._cash = 350;
        }
    
        get cash() {
            return this._cash;
        }
    
        set cash(value) {
            this._cash = value;
        }
    };
    

    Another one using Object.defineProperty:

    class Player {
        constructor(id) {
            this.id = id;
    
            var _cash = 350;
            Object.defineProperty(this, 'cash', {
                get: function() {
                    return _cash;
                }
    
                set: function(v) {
                    _cash = v;
                }
            });
        }
    };
    

提交回复
热议问题