JSON.stringify function

后端 未结 5 875
谎友^
谎友^ 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条回答
  • 2020-11-27 05:22

    There is a way to serialize a function in JS, but you'll have to eval it on the other side and it will also lose access to it's original scope. A way to do it would be:

    JSON.stringify(objWithFunction, function(key, val) {
      if (typeof val === 'function') {
        return val + ''; // implicitly `toString` it
      }
      return val;
    });
    

    There are some legitimate uses for what you're asking despite what people are posting here, however, it all depends on what you're going to be using this for. There may be a better way of going about whatever it is you're trying to do.

    0 讨论(0)
  • 2020-11-27 05:22

    In fact, It's very easy to serealize / parse javascript object with methods.

    Take a look at JSONfn plugin.

    http://www.eslinstructor.net/jsonfn/

    Hope this helps.

    -Vadim

    0 讨论(0)
  • 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()

    0 讨论(0)
  • 2020-11-27 05:32

    Here's some code I have used in my previous projects, maybe useful?

      // Similar to JSON.stringify(), with three major differences:
      // (1) It also wrap functions
      // (2) Upon execution, it expose an object, nl, into the scope
      // (3) Results are minified by 'uglify-js'
      var bundle = function(obj) {
        var type = typeof obj;
        if(type === 'string') return '\'' + obj + '\'';
        if(type === 'boolean' || type === 'number') return obj;
        if(type === 'function') return obj.toString();
        var ret = [];
        for(var prop in obj) {
          ret.push(prop + ': ' + bundle(obj[prop]));
        }
        return '{' + ret.join(',') + '}';
      };
      var ret = 'var nl = ' + bundle(nl);
      ret = require('uglify-js').minify(ret, {fromString: true}).code;
      fs.writeFileSync('nl.js', ret);
    

    One Caveat when using this is that if the function uses anything in external closure, it won't work, ie: ... obj: {..., key: (function() {...var a = 10;... return function() {... some code uses 'a'...})()}

    0 讨论(0)
  • 2020-11-27 05:41

    Why exactly do you want to stringify the object? JSON doesn't understand functions (and it's not supposed to). If you want to pass around objects why not do it one of the following ways?

    var x = {name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628};
    
    function y(obj) {
        obj.load();
    }
    
    // works
    y({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628});
    
    // "safer"
    y(({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628}));
    
    // how it's supposed to be done
    y(x);
    
    0 讨论(0)
提交回复
热议问题