You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

24 lines
816 B
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 自定义序列化方法解决JSON.stringify方法忽略函数属性的问题
export function customSerialize (obj) {
// 将对象属性和函数转换为字符串形式
const serializedObj = JSON.stringify(obj, function(key, value) {
if (typeof value === 'function') {
return value.toString() // 将函数转换为字符串
}
return value // 保持其他属性不变
})
return serializedObj
}
// 自定义反序列化方法
export function customDeserialize(serializedObj){
const parsedObject = JSON.parse(serializedObj, function(key, value) {
if (typeof value === 'string' && value.indexOf('function') === 0) {
// 将字符串还原为函数
return new Function('return ' + value)()
}
return value // 保持其他属性不变
})
return parsedObject
}