function MyClass() {
this.foo = "foo";
this.bar = "bar";
}
MyClass.prototype.toJSON = function(space) {
if (typeof space === 'undefined') space = 4;
return JSON.stringify(this, null, space);
};
var m = new MyClass();
console.log(m.toJSON());
I ran it in node.js, and got:
MyClass.prototype.toJSON = function(space) {
^
RangeError: Maximum call stack size exceeded
I don't know why. It makes me confused. Could you please tell me the reason causing this error? And how to fix it?
thisin your.toJSONmethod is a reference tomandstringifywill invoke a.toJSONmethod if it exists on the data it's given. Som.toJSON()callsJSON.stringify(m..., which callsm.toJSON(), which callsJSON.stringify(m..., and so on.cookie monster, not just a comment. Here's a comment: You should changeif (typeof space === 'undefined') space = 4;tovar spc = space ? space : 4;. Then passspctoJSON.stringify(), as the last argument.spacecould assign a global variable.