I'm moving from using the hacky JavaScript classes of old (functions and prototypes) to the new ES6 classes.
I'm probably doing something stupid but I'm not sure why I'm not allowed to do this:
class Player{ constructor(playerNo){ this.playerNo = playerNo; } get playerNo(){ return this.playerNo; } set cards(playersCards){ this.cards = playersCards; } get cards(){ return this.cards; } } var steve = new Player(1);
It gives me the error: Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4
So, I tried the below:
class Player{ constructor(playerNo){ this.playerNo = playerNo; } set playerNo(no){ this.playerNo = no; } get playerNo(){ return this.playerNo; } set cards(playersCards){ this.cards = playersCards; } get cards(){ return this.cards; } } var steve = new Player(1);
Which gives me: Uncaught RangeError: Maximum call stack size exceeded on line 6
(which is the line this.playerNo = no;
).
Any ideas?
You have recursion with setting playerNo
.
In the playerNo
setter, try setting this._playerNo = 0
.
In the rest of the code, continue to make a distinction between the name of the setter method and the internal property that stores the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With