我有一个JavaScript ES6类,它具有一个属性集,set并通过get函数进行访问.它也是一个构造函数参数,因此可以使用所述属性实例化该类.
class MyClass {
constructor(property) {
this.property = property
}
set property(prop) {
// Some validation etc.
this._property = prop
}
get property() {
return this._property
}
}
Run Code Online (Sandbox Code Playgroud)
我_property用来逃避使用get/set的JS问题,如果我直接设置它会导致无限循环property.
现在我需要对MyClass的一个实例进行字符串化,以便通过HTTP请求发送它.字符串化的JSON是一个对象,如:
{
//...
_property:
}
Run Code Online (Sandbox Code Playgroud)
我需要保留生成的JSON字符串,property以便我发送给它的服务可以正确解析它.我还需要property保留在构造函数中,因为我需要从服务发送的JSON构造MyClass的实例(它发送property没有的对象_property).
我该如何解决这个问题?如果我只是把它发送到HTTP请求之前截获MyClass的实例,并发生变异_property,以property使用正则表达式?这看起来很难看,但我能够保留当前的代码.
或者,我可以拦截从服务发送到客户端的JSON,并使用完全不同的属性名称实例化MyClass.但是,这意味着服务两侧的类的不同表示.