[英]ES6 classes - Wrong constructor and setters behavior
当实例的某些属性更改时,我需要使用setters
洞察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
吸气剂,所以为什么要不确定。
这this.xPos = 0;
调用xPos
setter,但是当您要编写值时,它将为它找到一个变量或一个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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.