Unique Scenario
Upon discovering this answer, a new idea struck me - creating an object from a JSON literal.
This led me to believe I could do the opposite using the handy JSON method:
JSON.stringify(myObject)
.
Curious, I proceeded as follows:
function MyObject(id, value, desc)
{
this.id = id;
this.value = value;
this.desc = desc;
this.toJSON = function()
{
return JSON.stringify(this);
}
}
However, upon running this code (demo), it threw a Maximum call stack size exceeded
error.
After some searching, I came across two resources explaining this behavior:
- the JSON.stringify() method on MDN.
- the JSON in Javascript article on JSON.org
It seems that .toJSON
overrides the .stringify
method, leading to a loop when called within itself.
Thought-provoking Questions
- (general) Why was the design choice made for
toJSON
? Is it a reserved or special keyword? - (specific) To resolve the stack overflow issue, I opted to rename
.toJSON
to.display
, which felt somewhat inelegant. Are there alternative solutions?