Why can't you stringify a function expression?

浪子不回头ぞ 提交于 2019-11-29 12:06:05

问题


Why doesn't this produce anything?

console.log(JSON.stringify(function(){console.log('foobar');}));

回答1:


JSON can't stringify functions at all, it handles them just like undefined or null values. You can check the exact algorithm at EcmaScript 5.1 §15.12.3, see also the description at MDN.

However you of course can stringify function expression by casting them to a string, try

console.log("" + function(){console.log('foobar');})



回答2:


JSON has no means to represent a function. It is a data format designed for simplicity and compatibility across languages (and a function is the last thing that will be cross-language compatible).

From the docs for JSON.stringify:

If undefined, a function, or an XML value is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).




回答3:


You cannot do that, but there are some third party libraries can help you do that, like: https://www.npmjs.com/package/json-fn




回答4:


If you want to use JSON.stringify to also convert functions and native objects you can pass a converter function as the second argument:

const data = {
  fn: function(){}
}

function converter(key, val) {
  if (val && typeof val === 'function' || val.constructor === RegExp) {
    return String(val)
  }
  return val
}

console.log(JSON.stringify(data, converter, 2))

Return undefined from the converter function if you want to omit the result.

The third parameter is how many spaces you want the output to indent (optional).




回答5:


yourFunctionName.toString(); will also stringify a function



来源:https://stackoverflow.com/questions/12651977/why-cant-you-stringify-a-function-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!