Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4

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?

like image 601
Jonah Avatar asked Apr 11 '16 15:04

Jonah


1 Answers

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.

like image 174
Mark Stosberg Avatar answered Sep 22 '22 08:09

Mark Stosberg