javascript get function body

后端 未结 8 1673
一整个雨季
一整个雨季 2020-12-01 05:44

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

8条回答
  •  攒了一身酷
    2020-12-01 06:14

    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);"
    

提交回复
热议问题