-4

如何遍历对象/数组并将所有函数转换为唯一 ID?

有一点像

JSON.stringify

但仅适用于功能

Function.stringify(obj/arr)

var sum = function(a,b){return a+b}

Function.stringify({
   foo: sum,
   bar: [{
      baz: [["foo", "bar"], "baz", function(){}]
   }]
})

// returns 

{
   foo: "func01",
   bar: [{
      baz: [["foo", "bar"], "baz", "func02"]
   }]
}
4

4 回答 4

2

类似于以下内容,尽管我没有为函数计数器的填充而烦恼:

var mySerializer = function () {
  var counter = 0;

  return function serialize(input, stack, reset) {
    var result, prop, funcId, i;

    if (reset) {
      counter = 0;
    }

    if (typeof stack !== 'object') {
      stack = {};
    }

    switch (typeof input) {
      // input is object
      case 'object':
        result = {};
        for (prop in input) {
          if (input.hasOwnProperty(prop)) {
            result[prop] = serialize(input[prop], stack, false);
          }
        }
        break;

      // input is array
      case 'array':
        result = [];
        for (i = 0; i < input.length; i += 1) {
          result.push(serialize(input[i], stack, false));
        }
        break;

      case 'function':
        funcId = ['func', ++counter].join('');
        funcs[funcId] = input;
        return funcId;

      // default
      default:
        return input;
    }

    return result;
  };
}();

var
  sum = function(a,b){ return a+b; },
  funcs = {},
  result = mySerializer({
    foo: sum,
    bar: [{
      baz: [["foo", "bar"], "baz", function(){}]
    }]
  }, funcs); // supply empty object, which will be used to stored replaced functions

console.log(result, funcs);

演示:http: //jsbin.com/ujahub/1/


更新以使“替换”功能可访问。

于 2013-04-16T16:06:03.267 回答
1

您可以将第二个参数用于JSON.stringify: replacer:

function func() {}
var data = {
    "some data": func
};
JSON.stringify(data, function (key, value) {
    if (value === func) {
        return "**func";
    }
    return value;
});
// output: {"some data": "**func"}

更改此代码以处理任意数量的函数很容易。

这确实需要您了解所有功能,并且反序列化也是一个问题。

于 2013-04-16T15:54:41.817 回答
0

只是为了好玩...

function getAllFunctions()
{
   var functionBodies = [];

    //iterate through keys of window object
    for (var f in window) 
    {
        if (window.hasOwnProperty(f) && typeof window[f] === 'function')
        {
            //ignore native functions
            if(window[f].toString().match(/(\[native code\]|\[object Function\])/g) == null)
            {
                functionBodies.push(window[f].toString());
            }
        }
    }

    return functionBodies.join('\n\n');
}
于 2013-04-16T16:15:15.590 回答
0

根据 Frits 的想法,我想出了自己的解决方案

var id = 0;
func = {};

function mySerializer(data){
    return JSON.parse(JSON.stringify(data, function (key, value) {
        if (typeof value === "function") {
            func["func"+id] = value;
            id++;
            return "func"+id;
        }
        return value;
    }));
}

var sum = function(a,b){ return a+b; };

console.log(mySerializer({
   foo: sum,
   bar: [{
      baz: [["foo", "bar"], "baz", function(){}]
   }]
}));
于 2013-04-16T16:17:59.197 回答