覆盖 JSON.stringify 导致错误 [英] Overriding JSON.stringify causing error

查看:56
本文介绍了覆盖 JSON.stringify 导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚创建了一个像这样返回 JSON.stringify 的函数:

I just created a function that return JSON.stringify like this:

JSON.stringify = function (item, replacer, space) {
     return JSON.stringify(item, replacer, space);
}

它会在 angularjs 上导致所有这些错误:点击此处

and it causes all these errors on angularjs: click here

我想覆盖函数的原因是因为我想在对象中创建一个属性,告诉 JSON 忽略一个字段,如下所示:

The reason I want to override the function is because I want to create a property in objects that tells the JSON to ignore a field, like this:

JSON.stringify = function (item, replacer, space) {
    if (angular.isObject(item)) {
        var newItem = angular.copy(item);
        var ignores = item.jsonIgnore || [];

        ignores.forEach(prop => {
            delete newItem[prop];
        });

        return JSON.stringify(newItem, replacer, space);
    }

    return JSON.stringify(item, replacer, space);
}

推荐答案

谢谢大家,我解决了用原函数创建局部变量

Thanks all, I resolved creating a local variable with the original function

var originalStringify = JSON.stringify;

然后调用我的自定义函数

and then calling on my custom function

return originalStringify(item, replacer, space);

现在我完整的 Json 忽略覆盖功能是这样的:

Now my full Json ignore override function is like this:

// JSON ignore
var original = JSON.stringify;

JSON.stringify = function (item, replacer, space) {
    if (angular.isObject(item)) {
        var newItem = angular.copy(item);
        var ignores = item.jsonIgnore || [];

        ignores.forEach(prop => {
            delete newItem[prop];
            delete newItem.jsonIgnore;
        });

        return original(newItem, replacer, space);
    }

    return original(item, replacer, space);
}

这篇关于覆盖 JSON.stringify 导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆