kil*_*wuk 13 javascript json prototype node.js
我一直在使用相当多的JSON解析并最近在Node.js和浏览器中传递Javascript并遇到了这个难题.
我使用构造函数创建的任何对象都无法通过JSON.stringify完全序列化,因此我单独初始化了构造函数中的所有值!这意味着我的原型在设计这些类时基本上没用.
有人可以解释为什么以下不像我预期的那样序列化吗?
var ClassA = function () { this.initialisedValue = "You can see me!" };
ClassA.prototype = { initialisedValue : "You can't see me!", uninitialisedValue : "You can't see me!" };
var a = new ClassA();
var a_string = JSON.stringify(a);
Run Code Online (Sandbox Code Playgroud)
怎么了:
a_string == {"initialisedValue":"你可以看到我!" }
我希望:
a_string == {"initialisedValue":"你可以看到我!","uninitialisedValue":"你看不到我!" }
Jam*_*ice 14
只是因为这是JSON的工作方式.从ES5规范:
设K是一个内部字符串列表,由[[Enumerable]]属性为true 的所有值属性的名称组成.
这是有道理的,因为JSON规范中没有用于保留在包含继承属性时将JSON字符串解析回JavaScript对象所需的信息的机制.在您的示例中,如何解析:
{"initialisedValue":"你可以看到我!","uninitialisedValue":"你看不到我!" }
除了具有2个键值对的扁平对象之外,没有任何信息可以将其解析为任何其他内容.
如果你考虑一下,JSON并不打算直接映射到JavaScript对象.其他语言必须能够将JSON字符串解析为名称 - 值对的简单结构.如果JSON字符串包含序列化完整JavaScript范围链所需的所有信息,则其他语言可能无法将其解析为有用的东西.用json.org上Douglas Crockford的话来说:
这些[哈希表和数组]是通用数据结构.实际上,所有现代编程语言都以某种形式支持它们.有意义的是,可与编程语言互换的数据格式也基于这些结构.
我想补充一点,尽管JSON.stringify只会对对象自己的属性进行字符串化,如已接受的答案中所述,您可以通过指定一个数组String作为JSON.stringify(称为替换器数组)的第二个参数来改变字符串化过程的行为.
如果您指定一个String带有要字符串化的属性白名单的数组,则字符串化算法将改变其行为并考虑原型链中的属性。
从ES5 规范:
如果 PropertyList 不是未定义的,则
一种。令 K 为 PropertyList。
别的
a. Let K be an internal List of Strings consisting of the names of all the own properties of value whose [[Enumerable]] attribute is true. The ordering of the Strings should be the same as that used by the Object.keys standard built-in function.
If you know the name of the properties of the object to stringify beforehand, you can do something like this:
var a_string = JSON.stringify(a, ["initialisedValue", "uninitialisedValue"]);
// a_string == { "initialisedValue" : "You can see me!", "uninitialisedValue" : "You can't see me!" }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5628 次 |
| 最近记录: |