javascript get function body

后端 未结 8 1681
一整个雨季
一整个雨季 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: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.

提交回复
热议问题