ECMAScript 6类属性下划线前缀

vco*_*rea 6 javascript node.js ecmascript-6 es6-class

我见过的类模式几乎都是这样的:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

console.log(new Foo('x', 'y', 'z')) 执行输出:

Foo { _x: 'x', _y: 'y', _z: 'z' }
Run Code Online (Sandbox Code Playgroud)

console.log(JSON.stringify(new Foo('x', 'y', 'z'))) 执行输出:

{"_x":"x","_y":"y","_z":"z"}
Run Code Online (Sandbox Code Playgroud)

这给了我下划线前缀字段,我没有瞄准,我怎么能让字段没有下划线前缀,然而,有instance.prop交互触发的getter和setter .

gen*_*nry 11

您可以添加一个toJSON方法来调整输出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));
Run Code Online (Sandbox Code Playgroud)

输出: "{"x":"x","y":"y","z":"z"}"


Nem*_*X00 5

如果您的问题确实只是下划线,那么您可以尝试使用更类似于C#属性的命名约定,其中get/set方法使用PascalCase,但成员变量使用camelCase,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

最终,由于对象在ECMAScript 6中的工作方式,因此无法同时将成员变量和get/set方法命名为100%.事实上,这就是为什么使用下划线格式是如此常见.下划线告诉任何查看代码的人,该属性是"私有的".在ECMAScript 6中,私有成员的概念并不存在.