Can Javascript get a function as text? I'm thinking like the inverse of eval().
function derp() { a(); b(); c(); } alert(derp.asString());
The result would be something like "a(); b(); c();"
Does it exist?
To convert a function to string, use the toString() method of a function object.
In JavaScript, we can make functions that are able to return a value. To create such type of function, we have to use the return statement, but it must be the last statement in the body of the function (or in the definition of the function).
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
You can display output in JavaScript using any of the following ways: To display output in the browser console, you can use the “console. log()” function. To write out into HTML and display its output, you can use the “document.
In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code. Surely, a function is a special value, in the sense that we can call it like sayHi ().
When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.
The closest thing available to what you're after is calling .toString () on a function to get the full function text, like this: You can give it a try here, some caveats to be aware of though:
Such functions are not accessible outside of ask (because they are not assigned to variables), but that’s just what we want here. Such code appears in our scripts very naturally, it’s in the spirit of JavaScript. Regular values like strings or numbers represent the data.
Updated to include caveats in the comments below from CMS, Tim Down, MooGoo:
The closest thing available to what you're after is calling .toString()
on a function to get the full function text, like this:
function derp() { a(); b(); c(); } alert(derp.toString()); //"function derp() { a(); b(); c(); }"
You can give it a try here, some caveats to be aware of though:
.toString()
on function is implementation-dependent (Spec here section 15.3.4.2) (function() { x=5; 1+2+3; }).toString()
== function() { x=5; }
function derp() { a(); b(); c(); } alert(derp.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With