I need to use setters insight ES6 classes to call some method automatically when some properties of a instance are changed.
I wrote this:
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();
But the console outputs:
xPos undefined
yPos undefined
You don't have getters for xPos and yPos, so why you get undefined.
This this.xPos = 0; calls setter for xPos, but when you want to write the value, it is going to find a variable or a getter for it, but you don't have any of them. In you case you need to work with value, or write a getter for it.
In the example I am working through getters and setters. In setter I set the value for properties and read throw getter. The getter returns the propertie's value.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With