原型上的Object.defineProperty阻止JSON.stringify序列化它 [英] Object.defineProperty on a prototype prevents JSON.stringify from serializing it

查看:350
本文介绍了原型上的Object.defineProperty阻止JSON.stringify序列化它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TypeScript来定义一些类,当我创建一个属性时,它会在以下plunkr中生成等效于 Class1

I'm using TypeScript to define some classes and when I create a property, it generates the equivalent to Class1 in the following plunkr:

http://plnkr.co/edit/NXUo7zjJZaUuyv54TD9i?p=preview

var Class1 = function () {
  this._name = "test1";
}

Object.defineProperty(Class1.prototype, "Name", {
  get: function() { return this._name; },
  set: function(value) { this._name = value; },
  enumerable: true
});

JSON.stringify(new Class1()); // Will be "{"_name":"test1"}"

序列化时,它不会'输出我刚刚定义的属性。

When serializing, it doesn't output the property I just defined.

instance2 instance3 通过序列化已定义的属性来表现我的期望。 (参见plunkr输出)。

instance2 and instance3 behave as I'd expect by serializing the defined property. (see the plunkr output).

我的实际问题是:这是正常的吗?

My actual question is: Is this normal?

如果是这样,如何我能以最有效的方式解决这个问题吗?

If so, how do I work around it in the most efficient way?

推荐答案

你可以定义一个 toJSON() 方法自定义实例的序列化方式。

You can define a toJSON() method on your prototype to customize how instances are serialized.

Class1.prototype.toJSON = function () {
    return {
        Name: this.Name
    };
};
JSON.stringify(new Class1()); // Will be '{"Name":"test1"}'

这篇关于原型上的Object.defineProperty阻止JSON.stringify序列化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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