Simplest Use-Case
If you just want to execute the body of the function (e.g. with eval
or using the Worker
API), you can simply add some code to circumvent all the pitfalls of extracting the body of the function (which, as mentioned by others, is a bad idea in general):
'(' + myFunction + ')()';
I am using this trick in this Worker
-related JSFiddle.
Complete Function Serialization With Accurate Stacktrace
I also wrote a more complete library that can:
- Serialize any kind of function to string
- Be able to send that string representation anywhere else, execute it with any custom arguments, and be able to reproduce the original stacktrace
Check out my CodeBuilder
code here.
Note that much of the code takes care of making sure that we get an accurate stacktrace, wherever we execute the serialized function at a later point in time.
This fiddle demonstrates a simplified version of that logic:
- Use
JSON.stringify
to properly serialize the function (that comes in handy when, e.g., we want to make it part of a bigger serialization "data package").
- We then wrap it in one
eval
to un-escape the "JSON-ish"-escaped string (JSON does not allow functions + code, so we must use eval
), and then in another eval
to get back the object we wanted.
- We also use
//# sourceMappingURL
(or the old version //@ sourceMappingURL
) to show the right function name in the stacktrace.
- You will find that the Stacktrace looks Ok, but it does not give you the correct row and column information relative to the file that we defined the serialized functions in, which is why my
Codebuilder
makes use of stacktracejs to fix that.
I use the CodeBuilder
stuff in my (now slightly dated) RPC library where you can find some examples of how it is used:
serializeInlineFunction
example
serializeFunction
example
buildFunctionCall
example