Convert Javascript Object (incl. functions) to String

后端 未结 10 1034
你的背包
你的背包 2020-12-29 21:35

Hey, Im trying to convert specific javascript objects to a String. So far I\'m working with json2.js. As soon as my Object contain functions, those functions are stripped. I

10条回答
  •  时光取名叫无心
    2020-12-29 22:02

    Just provide the object to this function. (Look for nested function) Here:

    function reviveJS(obj) {
      return JSON.parse(JSON.stringify(obj, function (k, v) {
        if (typeof v === 'function') {
          return '__fn__' + v;
        }
        return v;
      }), function (k, v) {
        if (typeof v === 'string' && v.indexOf('__fn__') !== -1) {
          return v;
        }
        return v;
      });
    }

    UPDATE

    A slightly decent code than above which I was able to solve is here http://jsfiddle.net/shobhit_sharma/edxwf0at/

提交回复
热议问题