JSON.stringify function

后端 未结 5 894
谎友^
谎友^ 2020-11-27 04:56

I have an object that has some properties and methods, like so:

{name: \"FirstName\",
age: \"19\",
load: function () {},
uniq: 0.5233059714082628}

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 05:27

    Not something I would ever do but it is worth mentioning that there are ways to stringify function (i.e. it is not impossible).

    Take the following:

    var func = function(){console.log('logged')};
    var strFunc = func.toString();
    
    //then
    var parsedFunc = eval('('+strFunc+')');
    parsedFunc();
    
    //or simply
    eval('('+strFunc+')()');
    //or
    eval('('+strFunc+')')();
    //or
    eval('var anotherFunc='+strFunc);
    anotherFunc()
    

    The above with an overridden toJSON() can achieve a shallow stringified function;

    DISCLAIMER: look into this and other articles and make your own decision before using eval()

提交回复
热议问题