How to get a functions's body as string?

后端 未结 4 1431
不思量自难忘°
不思量自难忘° 2020-12-06 17:07

I want to know how to convert a function\'s body into a string?

function A(){
  alert(1);
}

output = eval(A).toString() // this will come with  function A()         


        
4条回答
  •  再見小時候
    2020-12-06 17:48

    You could just stringify the function and extract the body by removing everything else:

    A.toString().replace(/^function\s*\S+\s*\([^)]*\)\s*\{|\}$/g, "");
    

    However, there is no good reason to do that and toString actually doesn't work in all environments.

提交回复
热议问题