如何在JavaScript中获取函数体文本?

时间:2012-09-01 12:30:46

标签: javascript function

function derp() { a(); b(); c(); }

derp.toString()将返回"function derp() { a(); b(); c(); }",但我只需要函数体,所以"a(); b(); c();",因为我可以评估表达式。是否可以以跨浏览器的方式执行此操作?

5 个答案:

答案 0 :(得分:37)

var entire = derp.toString(); 
var body = entire.slice(entire.indexOf("{") + 1, entire.lastIndexOf("}"));

console.log(body); // "a(); b(); c();"

请使用搜索,这与this question

重复

答案 1 :(得分:5)

当然,因为您需要在第一个{和最后一个}之间的文字:

derp.toString.replace(/^[^{]*{\s*/,'').replace(/\s*}[^}]*$/,'');

请注意,我将替换分解为正则表达式,而不是覆盖整个事物(.replace(/^[^{]*{\s*([\d\D]*)\s*}[^}]*$/,'$1'))的一个正则表达式,因为它的内存密集程度要低得多。

答案 2 :(得分:4)

注意:接受的答案取决于口译员没有做过像'function'和'{'之间的回复评论这样的疯狂事情。 IE8很乐意这样做:

>>var x = function /* this is a counter-example { */ () {return "of the genre"};
>>x.toString();
"function /* this is a counter-example { */ () {return "of the genre"}"

答案 3 :(得分:2)

你需要这样的东西:

var content = derp.toString();
var body = content.match(/{[\w\W]*}/);
body = body.slice(1, body.length - 1);

console.log(body); // a(); b(); c();

答案 4 :(得分:2)

单行,短正则表达式示例:

var body = f.toString().match(/^[^{]+\{(.*?)\}$/)[1];

如果你想最终eval脚本,并假设函数没有参数,这应该会快一点:

var body = '(' + f.toString() + ')()';