javascript 为什么不能对函数表达式进行字符串化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12651977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't you stringify a function expression?
提问by wwaawaw
Why doesn't this produce anything?
为什么这不会产生任何东西?
console.log(JSON.stringify(function(){console.log('foobar');}));
回答by Bergi
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.
JSON 根本不能对函数进行字符串化,它像undefined
或null
值一样处理它们。您可以在EcmaScript 5.1 §15.12.3中查看确切的算法,另请参阅MDN 中的描述。
However you of course can stringify function expression by casting them to a string, try
但是,您当然可以通过将它们转换为字符串来对函数表达式进行字符串化,请尝试
console.log("" + function(){console.log('foobar');})
回答by Quentin
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).
JSON 无法表示函数。它是一种为简单性和跨语言兼容性而设计的数据格式(并且函数是跨语言兼容的最后一件事)。
From the docs for JSON.stringify:
来自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).
如果在转换过程中遇到未定义的函数或 XML 值,则将其省略(在对象中找到时)或删失为 null(在数组中找到时)。
回答by auraz
yourFunctionName.toString();
will also stringify a function
yourFunctionName.toString();
还将对函数进行字符串化
回答by Xin
You cannot do that, but there are some third party libraries can help you do that, like: https://www.npmjs.com/package/json-fn
您不能这样做,但有一些第三方库可以帮助您做到这一点,例如:https: //www.npmjs.com/package/json-fn
回答by Vidar
If you want to use JSON.stringify
to also convert functions and native objects you can pass a converter function as the second argument:
如果您还想用于JSON.stringify
转换函数和本机对象,您可以将转换器函数作为第二个参数传递:
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.
undefined
如果要省略结果,请从转换器函数返回。
The third parameter is how many spaces you want the output to indent (optional).
第三个参数是您希望输出缩进多少个空格(可选)。