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?
toJSON
is a kind of reserved of special keyword? - (specific) I solved the stackoverflow bug changing the
.toJSON
name into.display
. Not so elegant. Is there another solution?