首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JSON使用getter/setter对ES6类属性进行字符串处理

JSON使用getter/setter对ES6类属性进行字符串处理
EN

Stack Overflow用户
提问于 2017-02-08 15:52:25
回答 4查看 15K关注 0票数 36

我有一个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。然而,这意味着服务两端的类都有不同的表示。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 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
    }
  }
}
票数 44
EN

Stack Overflow用户

发布于 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;
  }

}
票数 21
EN

Stack Overflow用户

发布于 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;
    }
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42107492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档