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-basics
谁能告诉我在 JSON
表示法中 representing an object
这两种方式的区别。我只是很困惑这些是实现相同还是有区别。
最佳答案
来自 fine manual :
toJSON behavior
If an object being stringified has a property named
toJSON
whose value is a function, then thetoJSON
method customizes JSON stringification behavior: instead of the object being serialized, the value returned by thetoJSON
method when called will be serialized.
这就是 Backbone 使用 toJSON
的原因。序列化方法并给定一个名为 m
的模型实例,您可以这样说:
var string = JSON.stringify(m);
只从 m
中获取属性,而不是你的服务器不会关心的一堆噪音。
也就是说,主要区别在于 toJSON
生成一个值(数字、 bool 值、对象...),该值被转换为 JSON 字符串,而 JSON.stringify
总是产生一个字符串。
default Backbone toJSON
就是这样(对于模型):
return _.clone(this.attributes);
所以 m.toJSON()
为您提供模型属性的 shallow 副本。如果有数组或对象作为属性值,那么您将结束意外的引用共享。请注意 Backbone.Model#clone
还有suffers from this problem .
如果您想安全地克隆模型的数据,那么您可以通过 JSON.stringify
发送它,然后通过 JSON.parse
来获取深拷贝:
var data = JSON.parse(JSON.stringify(model_instance));
var cloned_model = new M(data);
其中 model_instance
是 Backbone 模型 M
的实例。
https://stackoverflow.com/questions/20734894/