javascript - 学习OOP时失败 `JSON.stringify(this)`(得到RangeError : Maximum call stack size exceeded)

标签 javascript oop stack-overflow

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/

相关文章:

f# - 64 位 F#/FSI : Limitation of very large single file function

javascript - 如何检查子对象中是否包含 id?

javascript - Angular2 输出/发射()不工作

javascript - 模板字符串上的 netbeans javascript 错误(反引号)

c# - 设置DataGridView中的最大行数?

c# - 不是按名称而是按类型指定接口(interface)成员

c++ - 使用 goto 来避免深层函数调用中的堆栈溢出是个好主意吗?

javascript - 如何使用 Nuxt 在 html 元素上设置 lang 属性?

java - 使用继承类名初始化抽象类列表的更好方法

memory - 将内存从 2GB 升级到 4GB 可以防止 Stack Overflow 异常吗?