A few days ago in the "talking about Json.stringify method" said his correct use posture, today, the next ToJSON method.
In fact, I think the goods with the toString a reason, he is to give the Stringify method is called when the string.
Take a look at the official MDN document "ToJSON behavior".
It's very simple, but it's important to note that he and the Stringify method have a slightly different second argument.
Because the second parameter of stringify is the callback function, only the value corresponding to the current key is modified.
ToJSON, however, modifies the current object.
For example:
var obj = { key: ' foo '};var ret = json.stringify (obj, function (k, v) { return k = = = "Key"? V.touppercase (): v;} ); Console.log (ret); var obj = { key: ' foo ', tojson:function () { return ' bar '; }}; var ret = json.stringify (obj); Console.log (ret);
The difference is very obvious, ToJSON's return value directly replaces the current object, while the stringify callback function simply modifies the current value.
Of course they have their own uses, so look at the need to choose to use just fine.
Well, just share it today.