toJSON() 和 JSON.Stringify() 的区别 [英] Difference between toJSON() and JSON.Stringify()
问题描述
如果您需要读取或克隆模型的所有数据属性,请使用其toJSON() 方法.此方法返回属性的副本作为对象(尽管它的名字不是 JSON 字符串).(当 JSON.stringify() 是传递一个带有 toJSON() 方法的对象,它将返回字符串化toJSON() 的值而不是原始对象.中的例子上一节在调用时利用了此功能JSON.stringify() 记录模型实例.)
if you need to read or clone all of a model’s data attributes, use its toJSON() method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When JSON.stringify() is passed an object with a toJSON() method, it stringifies the return value of toJSON() instead of the original object. The examples in the previous section took advantage of this feature when they called JSON.stringify() to log model instances.)
http://addyosmani.github.io/backbone-fundamentals/#backbone-基础
谁能告诉我这两种用 JSON
表示法表示对象
的区别.我只是很困惑这些是否达到相同或不同.
Can anyone tell me the difference between both these ways of representing an object
in JSON
notation. I am just confused whether these to achieve the same or there is a difference.
推荐答案
来自 精美手册:
toJSON 行为
如果一个被字符串化的对象有一个名为 toJSON
的属性,它的值是一个函数,那么 toJSON
方法会自定义 JSON 字符串化行为:而不是对象被序列化,toJSON
方法在调用时返回的值将被序列化.
If an object being stringified has a property named toJSON
whose value is a function, then the toJSON
method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON
method when called will be serialized.
这就是 Backbone 使用 toJSON
方法进行序列化并给定一个名为 m
,你可以这样说:
This is why Backbone uses the toJSON
method for serialization and given a model instance called m
, you can say things like:
var string = JSON.stringify(m);
并且只从 m
中获取属性而不是一堆你的服务器不会关心的噪音.
and get just the attributes out of m
rather than a bunch of noise that your server won't care about.
也就是说,主要区别在于 toJSON
生成一个值(数字、布尔值、对象等),该值被转换为 JSON 字符串,而 JSON.stringify
总是产生一个字符串.
That said, the main difference is that toJSON
produces a value (a number, boolean, object, ...) that gets converted to a JSON string whereas JSON.stringify
always produces a string.
默认 Backbone toJSON
很简单这(对于模型):
The default Backbone toJSON
is simply this (for models):
return _.clone(this.attributes);
so m.toJSON()
为您提供模型属性的浅层 副本.如果有数组或对象作为属性值,那么您将结束意外的引用共享.请注意,Backbone.Model#clone
也遇到这个问题.
so m.toJSON()
gives you a shallow copy of the model's attributes. If there are arrays or objects as attribute values then you will end unexpected reference sharing. Note that Backbone.Model#clone
also suffers from this problem.
如果你想安全地克隆一个模型的数据,那么你可以通过 JSON.stringify
然后通过 JSON.parse
发送它以获得一个深层副本:
If you want to safely clone a model's data then you could send it through JSON.stringify
and then JSON.parse
to get a deep copy:
var data = JSON.parse(JSON.stringify(model_instance));
var cloned_model = new M(data);
其中 model_instance
是您的 Backbone 模型 M
的实例.
where model_instance
is your instance of the Backbone model M
.
这篇关于toJSON() 和 JSON.Stringify() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!