Mi sto spostando dall'uso delle classi JavaScript hacky di vecchie (funzioni e prototipi) alle nuove classi ES6.Unchaught TypeError: Impossibile impostare la proprietà playerNo of # che ha solo un getter sulla riga 4
Probabilmente sto facendo qualcosa di stupido, ma non sono sicuro perché io non sono autorizzato a farlo:
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);
Mi dà l'errore: Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4
Così, ho provato il qui di seguito:
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);
che mi dà: Uncaught RangeError: Maximum call stack size exceeded on line 6
(che è la linea this.playerNo = no;
).
Qualche idea?
Perché stai usando getter/setter qui? Non hai bisogno di loro. – Bergi
Sono buone pratiche, giusto? Inoltre, ho intenzione di implementare la convalida a breve, e senza setter che implichino il cambiamento del codice in molti luoghi. Quali motivi ci sono per non usarli? – Jonah
No, non sono buone pratiche quando non fanno nulla di speciale (e in aggiunta, sono piuttosto lenti). Semplicemente complicano il codice. Sì, puoi usarli * quando * applichi la convalida, va bene, ma non dovresti usarli fino a * allora *. – Bergi