Javascript ES6类-错误的构造函数和设置器行为
我需要使用Javascript ES6类-错误的构造函数和设置器行为,javascript,ecmascript-6,Javascript,Ecmascript 6,我需要使用settersinsightES6类在实例的某些属性发生更改时自动调用某些方法 我写道: class Some { constructor () { this.xPos = 0; this.yPos = 0; } set xPos (value) { console.log(`xPos ${this.xPos}`); } set yPos (value) { console.log(`yPos ${this.yPos}`);
setters
insightES6类
在实例的某些属性发生更改时自动调用某些方法
我写道:
class Some {
constructor () {
this.xPos = 0;
this.yPos = 0;
}
set xPos (value) {
console.log(`xPos ${this.xPos}`);
}
set yPos (value) {
console.log(`yPos ${this.yPos}`);
}
}
let some = new Some();
但是控制台输出:
xPos undefined
yPos undefined
您没有用于
xPos
和yPos
的getter,所以为什么要取消定义呢
ThisThis.xPos=0
为xPos
调用setter,但当您想要写入值时,它将为其找到一个变量或getter,但您没有任何变量或getter。在这种情况下,您需要使用value,或者为它编写一个getter
在本例中,我通过getters
和setters
工作。在setter
中,我设置属性的值,并读取throwgetter
。getter
返回属性的值
class一些{
构造函数(){
这个.xPos=0;
这1.yPos=0;
}
设置XPO(值){
this.xPosProp=值;
log(`xPos${this.xPos}`);
}
设置yPos(值){
this.yPosProp=值;
log(`yPos${this.yPos}`);
}
获取xpo(){
返回此.xPosProp;
}
获取yPos(){
返回此.yPosProp;
}
}
让一些=新的一些()所以如果我为某个道具提供setter,我必须为它提供getter?是否应该是这样的:get xPos(){return this.xPos}?@animatio如果要读取传递给该setter的值,可以must@animatio如果要存储数据,这里还需要一个属性