How to get a functions's body as string?

后端 未结 4 1429
不思量自难忘°
不思量自难忘° 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:33

    Currently, developers are using arrow functions with the new releases of Ecmascript.

    Hence, I would like to share the answer here which is the answer of Frank

        function getArrowFunctionBody(f) {
          const matches = f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){?([\s\S]*)}?$/);
          if (!matches) {
            return null;
          }
          
          const firstPass = matches[1];
          
          // Needed because the RegExp doesn't handle the last '}'.
          const secondPass =
            (firstPass.match(/{/g) || []).length === (firstPass.match(/}/g) || []).length - 1 ?
              firstPass.slice(0, firstPass.lastIndexOf('}')) :
              firstPass
          
          return secondPass;
        }
        
        const K = (x) => (y) => x;
        const I = (x) => (x);
        const V = (x) => (y) => (z) => z(x)(y);
        const f = (a, b) => {
          const c = a + b;
          return c;
        };
        const empty = () => { return undefined; };
        console.log(getArrowFunctionBody(K));
        console.log(getArrowFunctionBody(I));
        console.log(getArrowFunctionBody(V));
        console.log(getArrowFunctionBody(f));
        console.log(getArrowFunctionBody(empty));

    Original question here

提交回复
热议问题