func=function() {foo=true}
alert(JSON.stringify(func));
alerts "undefined"
obj={foo: true}
alert (JSON.stringify(obj));
alerts: "{foo: true}"
Have you ever wondered why JSON.stringify()
doesn't work for a "function object"? It seems that when trying to convert a function object into a JSON string, it just returns "undefined". This has raised some confusion among developers as objects are functions and vice versa in JavaScript. The Function constructor creates a new Function object, but the behavior of these objects seems to differ when converting them to a JSON string.
Searching for information on "function object" can be challenging with search engines as most results focus on how objects are functions and functions are objects in JavaScript. If every JavaScript function is an object, and every object is a function, why does
JSON.stringify(function() {foo=true})
not work as expected?
If your goal is simply to turn function() {foo=true}
into "function() {foo=true}"
, without looking for a workaround, the issue becomes clearer. It seems that the conversion process from function object to JSON string may have limitations due to the nature of how functions and objects are structured in JavaScript.
Visit this link to learn more about JavaScript Function objects.