JSON 使用 getter/setter 字符串化 ES6 类属性 [英] JSON stringify ES6 class property with getter/setter
问题描述
我有一个 JavaScript ES6 类,它有一个用 set
设置的属性,并用 get
函数访问.它也是一个构造函数参数,因此可以使用所述属性实例化该类.
I have a JavaScript ES6 class that has a property set with set
and accessed with get
functions. It is also a constructor parameter so the class can be instantiated with said property.
class MyClass {
constructor(property) {
this.property = property
}
set property(prop) {
// Some validation etc.
this._property = prop
}
get property() {
return this._property
}
}
我使用 _property
来逃避使用 get/set 的 JS 陷阱,如果我直接设置为 property
会导致无限循环.
I use _property
to escape the JS gotcha of using get/set that results in an infinite loop if I set directly to property
.
现在我需要将 MyClass 的一个实例字符串化以通过 HTTP 请求发送它.字符串化的 JSON 是一个对象,如:
Now I need to stringify an instance of MyClass to send it with a HTTP request. The stringified JSON is an object like:
{
//...
_property:
}
我需要生成的 JSON 字符串来保留 property
,以便我将其发送到的服务可以正确解析它.我还需要 property
保留在构造函数中,因为我需要从服务发送的 JSON 构造 MyClass 的实例(它发送带有 property
而不是 _property
).
I need the resulting JSON string to preserve property
so the service I am sending it to can parse it correctly. I also need property
to remain in the constructor because I need to construct instances of MyClass from JSON sent by the service (which is sending objects with property
not _property
).
我该如何解决这个问题?我应该在将 MyClass 实例发送到 HTTP 请求之前拦截它并使用正则表达式将 _property
变异为 property
吗?这看起来很难看,但我将能够保留我当前的代码.
How do I get around this? Should I just intercept the MyClass instance before sending it to the HTTP request and mutate _property
to property
using regex? This seems ugly, but I will be able to keep my current code.
或者,我可以拦截从服务发送到客户端的 JSON,并使用完全不同的属性名称实例化 MyClass.然而,这意味着服务两侧的类的表示不同.
Alternatively I can intercept the JSON being sent to the client from the service and instantiate MyClass with a totally different property name. However this means a different representation of the class either side of the service.
推荐答案
您可以使用 toJSON
方法 自定义您的类序列化为 JSON 的方式:
You can use toJSON
method to customise the way your class serialises to JSON:
class MyClass {
constructor(property) {
this.property = property
}
set property(prop) {
// Some validation etc.
this._property = prop
}
get property() {
return this._property
}
toJSON() {
return {
property: this.property
}
}
}
这篇关于JSON 使用 getter/setter 字符串化 ES6 类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!