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
insight
ES6类
在实例的某些属性发生更改时自动调用某些方法

我写道:

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,所以为什么要取消定义呢

This
This.xPos=0
xPos
调用setter,但当您想要写入值时,它将为其找到一个变量或getter,但您没有任何变量或getter。在这种情况下,您需要使用value,或者为它编写一个getter

在本例中,我通过
getters
setters
工作。在
setter
中,我设置属性的值,并读取throw
getter
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;
}
}

让一些=新的一些()