我有一个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
}
}
我使用_property
来避免使用get/set的JS陷阱,如果我直接设置为property
,它会导致无限循环。
现在,我需要对一个MyClass实例进行字符串化,以便将其与HTTP请求一起发送。字符串化的JSON是一个对象,如下所示:
{
//...
_property:
}
我需要生成的JSON字符串来保存property
,这样我发送它的服务才能正确地解析它。我还需要property
留在构造函数中,因为我需要从服务发送的MyClass构造MyClass的实例(它使用property
而不是_property
发送对象)。
我该如何解决这个问题呢?我是否应该在将MyClass实例发送到HTTP请求之前将其拦截,并使用正则表达式将_property
修改为property
?这看起来很丑陋,但我将能够保留我当前的代码。
或者,我可以截获从服务发送到客户机的JSON,并使用完全不同的属性名称实例化MyClass。然而,这意味着服务两端的类都有不同的表示。
发布于 2017-02-08 15:59:56
您可以使用toJSON
method定制您的类序列化为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
}
}
}
发布于 2017-03-09 21:17:11
如果您希望避免调用toJson,还有另一个使用enumerable和writable的解决方案:
class MyClass {
constructor(property) {
Object.defineProperties(this, {
_property: {writable: true, enumerable: false},
property: {
get: function () { return this._property; },
set: function (property) { this._property = property; },
enumerable: true
}
});
this.property = property;
}
}
发布于 2018-06-10 23:49:17
我对Alon Bar的脚本做了一些调整。下面是这个脚本的一个版本,它非常适合我。
toJSON() {
const jsonObj = Object.assign({}, this);
const proto = Object.getPrototypeOf(this);
for (const key of Object.getOwnPropertyNames(proto)) {
const desc = Object.getOwnPropertyDescriptor(proto, key);
const hasGetter = desc && typeof desc.get === 'function';
if (hasGetter) {
jsonObj[key] = this[key];
}
}
return jsonObj;
}
https://stackoverflow.com/questions/42107492
复制相似问题