Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some real world uses for function.toString()?

Tags:

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?

like image 803
Matthew Lock Avatar asked Aug 31 '09 07:08

Matthew Lock


2 Answers

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.

like image 25
jsdw Avatar answered Sep 28 '22 13:09

jsdw


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...

like image 77
Guffa Avatar answered Sep 28 '22 14:09

Guffa