Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ECMAScript 6 Class properties underscore prefix

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.

like image 674
vcorrea Avatar asked Nov 03 '16 17:11

vcorrea


1 Answers

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"}"

like image 194
generalhenry Avatar answered Sep 23 '22 00:09

generalhenry