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
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);"
var fn1 = function() {};
var fn2 = function() { alert("lol!"); };
Function.prototype.empty = function() {
var x = this.toString().match(/\s*function\s*\w*\s*\(.*?\)\s*{\s*}\s*;?\s*/);
return x != null;
};
alert(fn1.empty()); // true
alert(fn2.empty()); // false
' Solução proposta pelo Paulo Torres no grupo A.P.D.A. no facebook.