The Class patterns i've seen around pretty much comes to something like this:
class Foo {
constructor(x, y, z) {
this._x = x;
this._y = y;
this._z = z;
}
get x() {
return this._x;
}
set x(value) {
//I acctually do some stuff here
this._x = value;
}
get y() {
return this._y;
}
set y(value) {
//I acctually do some stuff here
this._y = value;
}
get z() {
return this._z;
}
set z(value) {
//I acctually do some stuff here
this._z = value;
}
}
console.log(new Foo('x', 'y', 'z'))
execution output:
Foo { _x: 'x', _y: 'y', _z: 'z' }
console.log(JSON.stringify(new Foo('x', 'y', 'z')))
execution output:
{"_x":"x","_y":"y","_z":"z"}
Which gives me underscore prefixed fields, and i wasnt aiming for that, how can i get the fields to have no underscore prefix, and yet, having getters and setters triggered by instance.prop
interaction.
You can add a toJSON
method to adjust the output of JSON.stringify
class Foo {
constructor(x, y, z) {
this._x = x;
this._y = y;
this._z = z;
}
get x() {
return this._x;
}
set x(value) {
this._x = value;
}
get y() {
return this._y;
}
set y(value) {
this._y = value;
}
get z() {
return this._z;
}
set z(value) {
this._z = value;
}
toJSON() {
return {
x: this._x,
y: this._y,
z: this._z
};
}
}
var foo = new Foo('x', 'y', 'z');
console.log(JSON.stringify(foo));
outputs: "{"x":"x","y":"y","z":"z"}"
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