Scenario
After reading this answer I realized that I could create object starting from a JSON literal.
So I guessed that I could do the opposite just using this useful JSON method:
JSON.stringify(myObject).
So I did as follow:
function MyObject(id, value, desc)
{
this.id = id;
this.value = value;
this.desc = desc;
this.toJSON = function()
{
return JSON.stringify(this);
}
}
But when I run this stuff (demo) a Maximum call stack size exceeded error occurs.
After googling a bit, I found two references that explain this behaviour:
- the JSON.stringify() method at MDN.
- the JSON in Javascript article at JSON.org
If I get right, .toJSON overrides the .stringify. So if the first one calls the second one a loop is generated.
Questions
- (general) Why this design choice?
toJSONis a kind of reserved of special keyword? - (specific) I solved the stackoverflow bug changing the
.toJSONname into.display. Not so elegant. Is there another solution?
Question 1, is
toJSONreserved?I’m not sure if it reserved, but for example the native Date object uses toJSON to create a stringified date representation:
Question 2, an easy solution:
create your custom stringify function that ignores toJSON methods (you may add it to the already existing global
JSON):now it’s very easy to use in all your objects:
To make it even more easy additionally add:
Now your objects might look like: