【发布时间】:2017-03-17 09:20:03
【问题描述】:
我见过的类模式几乎是这样的:
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'))执行输出:
Foo { _x: 'x', _y: 'y', _z: 'z' }
console.log(JSON.stringify(new Foo('x', 'y', 'z')))执行输出:
{"_x":"x","_y":"y","_z":"z"}
这给了我下划线前缀的字段,而我的目标不是这个,我怎样才能让字段没有下划线前缀,但是,有由instance.prop 交互触发的 getter 和 setter。
【问题讨论】:
-
我会说从变量后面删除 _ ?喜欢
constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } -
是的,在此示例中,与直接分配属性并跳过 getter 相比,优势为零。
-
@loganfsmyth 对不起这个糟糕的例子,但我实际上在我的
real world application中使用自定义设置器来设置属性,为了更好地理解,我编辑了我的 sn-p。 -
你用这个 JSON 数据做什么?我会说通常你不应该依赖类的 JSON 自动序列化,如果某物是一个类,你应该有一个方法,显式地或通过
.toJSON获取它的可序列化对象版本。 -
@loganfsmyth 现在,我只是使用本机驱动程序将数据保存在 mongodb 上(使用下划线保存属性),并在暴露的 JSON API 中返回它(在这种情况下,我使用 @987654330 @ 仅适用于我想省略我不想在前端结束的字段的类,例如密码)。
标签: javascript node.js ecmascript-6 es6-class