如何在 JavaScript 中获取函数正文?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12227735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:27:14  来源:igfitidea点击:

How to get function body text in JavaScript?

javascriptfunction

提问by greepow

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

derp.toString()will return "function derp() { a(); b(); c(); }", but I only need the body of the function, so "a(); b(); c();", because I can then evaluate the expression. Is it possible to do this in a cross-browser way?

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

回答by divide by zero

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

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

Please use the search, this is duplicate of this question

请使用搜索,这是这个问题的重复

回答by Niet the Dark Absol

Since you want the text between the first {and last }:

由于您想要 first{和 last之间的文本}

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

Note that I broke the replacement down into to regexes instead of one regex covering the whole thing (.replace(/^[^{]*{\s*([\d\D]*)\s*}[^}]*$/,'$1')) because it's much less memory-intensive.

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

回答by Ian

NOTE: The accepted answer depends on the interpreter not doing crazy things like throwing back comments between 'function' and '{'. IE8 will happily do this:

注意:接受的答案取决于解释器不会做一些疯狂的事情,比如在“函数”和“{”之间抛出注释。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"}"

回答by K3---rnc

A single-line, short regex example:

一个单行、简短的正则表达式示例:

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

If you want to, eventually, evalthe script, and assuming the function takes no parameters, this should be a tiny bit faster:

如果你最终想要eval脚本,并假设函数不带参数,这应该快一点:

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

回答by micnic

You need something like this:

你需要这样的东西:

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

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