我有一个关于如何在javascript中使用访问器和更改器的问题,因为有人教我为类的每个属性创建getter和setter,如下所述:
class card{
constructor(aSuit,aColor,aNumber)
{
this.suit = aSuit;
this.color = aColor;
this.number = aNumber;
}
get suit(){
return this._suit;
}
set suit(aSuit){
this._suit= aSuit;
}
get color(aColor){
return this._color;
}
set color(aColor){
this._color= aColor;
}
get number(){
return this._number;
}
set number(aNumber){
this._number= aNumber;
}
}
let card1 = new card("Spades","red",5);
console.log(card1.suit);
但是,我发现它没有放入getter中,而当我只是使用以下代码时,setter仍然产生相同的结果。
class card{
constructor(aSuit,aNumber)
{
this.suit = aSuit;
this.color = aColor;
this.number = aNumber;
}
}
let card1 = new card("Spades",5);
console.log(card1.suit);
我只是想知道我做错了什么。
我也很困惑为什么在访问器和mutators中,我被教导将其命名为this._suit,而不是this.suit。任何帮助将不胜感激