类似于以下内容,尽管我没有为函数计数器的填充而烦恼:
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/
更新以使“替换”功能可访问。