const a = {
test: 1,
func() {
console.log(1111)
}
}
const b = JSON.stringify(a)
console.log(b) // {"test":1}
如示例,在对一个包含function的对象进行JSON.stringify()时,function会被忽略掉,请问如何解决这种问题
###JSON 是一种数据的序列化、反序列化方案,而 function 不是数据,就更不是 JSON 的合法内容了。所以被舍弃掉才是正常的,没有“问题”,不需要“解决问题”。
如果你出于某种非常不合理的需求,需要把一个 function 序列化了,可以自己约定一种序列化方式。比如先 toString()
转成字符串;反序列化时 eval
。
function function2string(obj) {
if (!(obj instanceof Object))
throw new Error('不是对象,无法转换。');
if (obj === null)
return null;
const result = {};
for (let prop in obj) {
if (typeof obj[prop] === 'object') {
result[prop] = function2string(obj[prop]);
} else if (typeof obj[prop] === 'function') {
result[prop] = {
'@type': 'function',
'value': obj[prop].toString()
}
} else {
result[prop] = obj[prop];
}
}
return result;
}
const sample = function2string({
func: function() {
console.log(a);
}
});
console.log(JSON.stringify(sample));
反序列化就不写了,反过来 eval
就好了。
注:这种方式仅对自定义函数有效,对 ES 中内置函数无效。
###自己写个深拷贝方法。或者用lodash
库