JSON使用getter / setter引用ES6类属性 [英] JSON stringify ES6 class property with getter/setter

查看:528
本文介绍了JSON使用getter / setter引用ES6类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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 getcha,如果我直接设置则导致无限循环到属性

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字符串以保留属性所以我发送的服务可以正确解析。我还需要属性保留在构造函数中,因为我需要从服务发送的JSON中构造MyClass的实例(它是使用属性 not _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).

我该如何解决?在发送到HTTP请求之前应该拦截MyClass实例,并使用正则表达式将 _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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆