是否可以重写Function.prototype.toJSON,以便JSON.stringify可以与函数一起使用?

问题描述 投票:0回答:1

或者甚至可以重写JSON.parse的某些部分来解析函数?这不是时间敏感的,我在代码中构建了变通方法,但是使用eval函数,您会认为将函数转换为字符串然后返回就容易了。

javascript json prototype function-object to-json
1个回答
0
投票

这是可能,但很奇怪,您当然也无法访问已解析函数的任何外部范围。调用toString以获取函数的源代码,将括号修剪掉,以便仅获得函数主体,然后让Function.prototype.toJSON返回该函数体。然后在解析时,在字符串上调用new Function

Function.prototype.toJSON = function() {
  // trim out beginning and end {}s
  return this.toString().match(/[^{]*(?=}$)/)[0];
};

const fn = () => {
  console.log('foo');
};
const json = JSON.stringify({
  str: 'str',
  fn
});
console.log(json);
const parsed = JSON.parse(json);
const parsedFn = new Function(parsed.fn);
parsedFn();

但是在99%的情况下都不需要这样做。无论实际问题是什么,都有[[可能一个更优雅的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.