gpt4 book ai didi

javascript - ECMAScript 6 类属性下划线前缀

转载 作者:数据小太阳 更新时间:2023-10-29 04:56:54 24 4
gpt4 key购买 nike

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

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

这为我提供了带下划线前缀的字段,而我并不是为此而设计的,我如何才能让这些字段没有下划线前缀,同时让 getter 和 setter 由 instance.prop 交互触发。

最佳答案

您可以添加一个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));

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

关于javascript - ECMAScript 6 类属性下划线前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40407450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com