我需要使用 setters
insight ES6 classes
在实例的某些属性更改时自动调用某些方法。
我是这样写的:
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,所以你为什么会得到 undefined。
这个this.xPos = 0;
为xPos
调用了setter,但是当你要写值的时候,它会为它找一个变量或者getter ,但你没有任何一个。在你的情况下,你需要使用值,或者为它编写一个 getter。
在示例中,我正在使用 getters
和 setters
。在 setter
中,我设置属性值并读取 throw getter
。 getter
返回属性的值。
class Some {
constructor () {
this.xPos = 0;
this.yPos = 0;
}
set xPos (value) {
this.xPosProp = value;
console.log(`xPos ${this.xPos}`);
}
set yPos (value) {
this.yPosProp = value;
console.log(`yPos ${this.yPos}`);
}
get xPos () {
return this.xPosProp;
}
get yPos () {
return this.yPosProp;
}
}
let some = new Some();
关于javascript - ES6 类 - 错误的构造函数和 setter 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42834021/