Javascript-我们可以重写JSON.parse函数吗

Javascript-我们可以重写JSON.parse函数吗,javascript,Javascript,有没有一种方法可以重写JSON.parse函数 如果是,请为我提供覆盖它的方向。以下内容可以实现此目的: JSON.parse = function(str) { return { 'foo': 'bar' }; }; var res = JSON.parse('aaaa'); console.log(res); 下面应该可以做到这一点: JSON.parse = function(str) { return { 'foo': 'bar' }; }; var res = J

有没有一种方法可以重写JSON.parse函数


如果是,请为我提供覆盖它的方向。

以下内容可以实现此目的:

JSON.parse = function(str) {
    return { 'foo': 'bar' };
};

var res = JSON.parse('aaaa');
console.log(res);

下面应该可以做到这一点:

JSON.parse = function(str) {
    return { 'foo': 'bar' };
};

var res = JSON.parse('aaaa');
console.log(res);
是的,你可以

Object.getOwnPropertyDescriptor(JSON, 'parse')
> {writable: true, enumerable: false, configurable: true}
像这样

(function(JSON) {
   var oldParse = JSON.parse;

   JSON.parse = function newParse() {

   } 
}(JSON))
是的,你可以

Object.getOwnPropertyDescriptor(JSON, 'parse')
> {writable: true, enumerable: false, configurable: true}
像这样

(function(JSON) {
   var oldParse = JSON.parse;

   JSON.parse = function newParse() {

   } 
}(JSON))

这将对你有帮助

JSON.prototype.parse= function(str)
{
    // your custom code should be here
}
或者您可以为实现实际的JSON特性创建自定义JSON类

function CustomJSON() {};
CustomJSON.prototype = new JSON;
CustomJSON.prototype.__super__ = JSON;
CustomJSON.prototype.parse= function(str) {
    console.log('called CustomJSON.parse');

    // calling JSON.parse();
    this.__super__.prototype.parse.call(this);
};

这将对你有帮助

JSON.prototype.parse= function(str)
{
    // your custom code should be here
}
或者您可以为实现实际的JSON特性创建自定义JSON类

function CustomJSON() {};
CustomJSON.prototype = new JSON;
CustomJSON.prototype.__super__ = JSON;
CustomJSON.prototype.parse= function(str) {
    console.log('called CustomJSON.parse');

    // calling JSON.parse();
    this.__super__.prototype.parse.call(this);
};

您尝试过任何东西吗?是的,我尝试过使用以下内容,它正在工作-var JS_JSON_PARSE=JSON.PARSE;JSON.parse=function(a){//Write custom code return JS_JSON_parse(a)}的可能副本您尝试过什么吗?是的,我尝试过使用下面的方法,它正在工作-var JS_JSON_parse=JSON.parse;JSON.parse=function(a){//Write custom code return JS_JSON_parse(a);}感谢您的回复。在我的应用程序中,我在所有地方都使用了JSON.parse函数,现在我不想在每个地方修改代码来调用自定义函数。所以我打算用下面的方法。请告诉我这是否是一个好的做法,或者它会导致任何问题-
var JS_JSON_PARSE=JSON.PARSE;JSON.parse=function(a){//Write custom code return JS_JSON_parse(a)}
ok,没问题,但是如果你喜欢我的答案,别忘了投票。谢谢你的回复。在我的应用程序中,我在所有地方都使用了JSON.parse函数,现在我不想在每个地方修改代码来调用自定义函数。所以我打算用下面的方法。请告诉我这是否是一个好的做法,或者它会导致任何问题-
var JS_JSON_PARSE=JSON.PARSE;JSON.parse=function(a){//Write custom code return JS_JSON_parse(a)}
ok,没问题,但是如果你喜欢我的答案,别忘了投票。