是否可以覆盖 Function.prototype.toJSON 以便 JSON.stringify 可以使用函数?

Is it possible to override Function.prototype.toJSON so that JSON.stringify could work with functions?

或者甚至覆盖 JSON.parse 的某些部分来解析函数? 这对时间不敏感,我在我的代码中构建了解决方法,但是使用 eval 函数,您会认为将函数转换为字符串并返回是小菜一碟。

可能,但很奇怪,而且您当然无法访问已解析函数的任何外部范围。调用 toString 获取函数的源代码,调用 trim 括号,这样您就只有函数体了,还有 Function.prototype.toJSON return 那个。然后在解析的时候,对字符串调用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% 的情况下应该不需要这样做。无论实际问题是什么,可能 都有更优雅的解决方案。

我认为不需要去掉括号。我使用更简单的代码。它允许您将参数传递给您的函数:

Function.prototype.toJSON = function() {  return this.toString(); };

const json = JSON.stringify({ 
  func: (a,b) => { console.log(a,b); },
  a: 1
});

const parsed = JSON.parse(json);

const parsedFunc = Function('return ' + parsed.func + ';')();

parsedFunc('hello','world');