javascript 如何将函数体转换为字符串?

fruv7luv  于 2022-12-28  发布在  Java
关注(0)|答案(5)|浏览(323)

我想知道如何把函数体转换成字符串?

function A(){
  alert(1);
}

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

//output of output -> function A(){ alert(1); }

//How can I make output into alert(1); only???
ctzwtxfj

ctzwtxfj1#

如果你要做一些丑陋的事情,用regex来做:

A.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
o0lyfsai

o0lyfsai2#

不要使用正则表达式。

const getBody = (string) => string.substring(
  string.indexOf("{") + 1,
  string.lastIndexOf("}")
)

const f = () => { return 'yo' }
const g = function (some, params) { return 'hi' }
const h = () => "boom"

console.log(getBody(f.toString()))
console.log(getBody(g.toString()))
console.log(getBody(h.toString())) // fail !
v440hwme

v440hwme3#

你可以只对函数进行字符串化,然后通过移除其他所有内容来提取函数体:

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

但是,这样做并没有什么好的理由,而且toString实际上并不是在所有环境中都能工作。

dzjeubhm

dzjeubhm4#

目前,开发人员正在将箭头函数与新版本的Ecmascript一起使用。
因此,我想分享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));

原始question here

kknvjkwl

kknvjkwl5#

这可能就是你要找的

const toString = (func) => `(${func.toString()})()`
    
console.log(toString(() => {
    console.log("Hello world")
}))

这将执行函数。

相关问题