model.attributes和JSON.stringify之间的区别是什么

时间:2014-08-09 09:22:07

标签: backbone.js

model.attributesJSON.stringify之间的区别是什么?

也许有些prpberties,方法不落?

var Todo = Backbone.Model.extend({});
// We can then create our own concrete instance of a (Todo) model
// with no values at all:
var todo1 = new Todo();

// Following logs: {}
console.log(JSON.stringify(todo1));
console.log( todo1.attributes)

1 个答案:

答案 0 :(得分:2)

我在这里偷了@Daedalus的答案,但他是对的,JSON.stringify返回模型的字符串表示 - 没有两种方法。

你确定你并不意味着model.toJSON会返回一个浅层的属性副本吗?

var artist = new Backbone.Model({
  firstName: "Wassily",
  lastName: "Kandinsky"
});

artist.set({birthday: "December 16, 1866"});

// Object {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"} "object"
console.log(artist.attributes, typeof artist.attributes);

// Object {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"} "object"
console.log(artist.toJSON(), typeof artist.toJSON());

// {"firstName":"Wassily","lastName":"Kandinsky","birthday":"December 16, 1866"} string
console.log(JSON.stringify(artist), typeof JSON.stringify(artist));

小提琴:http://jsfiddle.net/ferahl/ftb83yuo/