javascript get function body

后端 未结 8 1647
一整个雨季
一整个雨季 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);"
    
    0 讨论(0)
  • 2020-12-01 06:15
    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.

    0 讨论(0)
提交回复
热议问题