javascript get function body

后端 未结 8 1702
一整个雨季
一整个雨季 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 05:55

    This code provides the body when using ES6 arrow functions like var testFn=(q)=>q+1;

    function getFunctionBody(test){  
        var entire = test.toString(); // note: not safe-guarded; this part may fail like this!
        return entire.substring((entire.indexOf("{")+1)||(entire.indexOf("=>")+2),  entire.lastIndexOf("}")!==-1?entire.lastIndexOf("}"):entire.length);
    }
    
    //testing/showcase code
    var tests = [
        function () {alert(1);},
        ()=>{return 1;},
        q=>q+1
    ];
    
    for (var i=0;i

    I originally submitted this code as an edit to polygenelubricants accepted answer, but it was rejected as the changes were considered to be too drastic.

提交回复
热议问题