I've noticed in JavaScript that if you define a function, say myfunction()
, and then call myfunction.toString()
, you get the text of the source for that function. Are there any interesting/real world uses of this?
This is an old question, but here are my 2 cents.
Using node.js, this becomes useful for creating functions on the serverside which are then embedded into a page and sent to the client.
For example, the dot.js template engine works by first compiling templates into a function, which can then be executed to generate the HTML code.
eg:
var compiled = dot.compile("<h1>{{=it.header}}</h1>");
var html_output = compiled({header: "hello world"});
So, if we want to make use of templates in the client without each client having to compile them first, we can serve them a page containing the evaluated result of:
"var compiled = " + dot.compile("<h1>{{=it.header}}</h1>").toString();
which will then provide a "compiled" function client-side, for use compiling data such as that sent from ajax requests into HTML client-side.
Well, you can use it to easily redefine a function:
function x() { alert('asdf'); }
eval(x.toString().replace('asdf','hello'));
x();
This will alert the string "hello" instead of the string "asdf".
This may be useful. On the other hand, self modifying code is often frowned upon because of the difficulty to maintain it...
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