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());
我在 node.js 中运行它,得到:
MyClass.prototype.toJSON = function(space) {
^
RangeError: Maximum call stack size exceeded
我不知道为什么。这让我很困惑。你能告诉我导致这个错误的原因吗?以及如何解决?
最佳答案
我通过将 .toJSON
函数重命名为 .save
解决了这个问题。
我在这里找到了原因:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify ,它说:
If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.
因此原始代码会导致无限递归。
感谢@cookie monster 和@PHPglue。
工作代码:
function MyClass() {
this.foo = "foo";
this.bar = "bar";
}
MyClass.prototype.save = function(space) {
var s = typeof space === 'undefined' ? 0 : 4;
return JSON.stringify(this, null, s);
};
var m = new MyClass();
console.log(m.save());
关于javascript - 学习OOP时失败 `JSON.stringify(this)`(得到RangeError : Maximum call stack size exceeded),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337162/