const evalFn = (fn) => {
var Fun = Function // 一个变量指向Function,防止前端编译工具报错
return new Fun('return ' + fn)()
}
/**
* * JSON反序列化,支持函数和 undefined
* @param data
*/
const JSONParse = (data) => {
return JSON.parse(data, (k, v) => {
// 过滤函数字符串
if (excludeParseEventKeyList.includes(k)) return v
// 过滤函数值表达式
if (typeof v === 'string') {
const someValue = excludeParseEventValueList.some(excludeValue => v.indexOf(excludeValue) > -1)
if (someValue) return v
}
// 还原函数值
if (typeof v === 'string' && v.indexOf && (v.indexOf('function') > -1 || v.indexOf('=>') > -1)) {
return evalFn(`(function(){return ${v}})()`)
} else if (typeof v === 'string' && v.indexOf && v.indexOf('return ') > -1) {
const baseLeftIndex = v.indexOf('(')
if (baseLeftIndex > -1) {
const newFn = `function ${v.substring(baseLeftIndex)}`
return evalFn(`(function(){return ${newFn}})()`)
}
}
return v
})
}
测试代码
let a2 = new Function(`return function () {
const a = {
b: '333'
}
return a }()`)()
标签:function,return,函数,indexOf,JSONParse,evalFn,const
From: https://www.cnblogs.com/pengchenggang/p/17879646.html