Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get function body

I have a function e.g.

var test = function () {alert(1);} 

How can I get the body of this function?

I assume that the only way is to parse the result of test.toString() method, but is there any other way? If parsing is the only way, what will be the regex to get to body? (help with the regex is extremly needed, because I am not familiar with them)

like image 412
kalan Avatar asked Jul 05 '10 13:07

kalan


People also ask

What is a function body JavaScript?

Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object.

How do you print a function in JavaScript?

JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").

What does toString () do in JavaScript?

toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.


1 Answers

IF(!!!) you can get the toString(), then you can simply take the substring from the first indexOf("{") to the lastIndexOf("}"). So, something like this "works" (as seen on ideone.com):

var test = function () {alert(1);}  var entire = test.toString(); // this part may fail! var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}"));  print(body); // "alert(1);" 
like image 67
polygenelubricants Avatar answered Sep 20 '22 06:09

polygenelubricants