Javascript 将函数的脚本内容转换为字符串

Javascript 将函数的脚本内容转换为字符串,javascript,Javascript,例如,如果我有这样的东西: function hello() {console.log("hello")} function hello() { console.log("hello"); } var f = hello.toString();//get string of whole function f = f.substring(f.indexOf('{') + 1);//remove declaration and opening bracket f = f.substrin

例如,如果我有这样的东西:

function hello() {console.log("hello")}
function hello() {
    console.log("hello");
}

var f = hello.toString();//get string of whole function
f = f.substring(f.indexOf('{') + 1);//remove declaration and opening bracket
f = f.substring(0, f.length - 1);//remove closing bracket
f = f.trim();//remove extra starting/eding whitespace

console.log(f);
我希望能够在java脚本中创建一个函数,该函数将返回字符串值:

"console.log("hello");"    

有没有办法用普通javascript实现这一点?

如果您使用
hello.toString()
它将输出
“function hello(){console.log(“hello”)}”
您可以通过调用函数上的
toString()
方法来获取所有代码,包括函数声明。然后可以解析该字符串以删除不需要的信息

大概是这样的:

function hello() {console.log("hello")}
function hello() {
    console.log("hello");
}

var f = hello.toString();//get string of whole function
f = f.substring(f.indexOf('{') + 1);//remove declaration and opening bracket
f = f.substring(0, f.length - 1);//remove closing bracket
f = f.trim();//remove extra starting/eding whitespace

console.log(f);

如果您直接基于创建的函数,但是如果您想创建一个文本字符串,那么其他人已经提供了正确的答案。只要恰当地引用它:

function hello() { return "console.log(\"hello\")"; };
无论如何,这应该在页面上显示
console.log(“hello”)

<html><head></head><body><script>
    function hello() { return "console.log(\"hello\")"; };
    document.write(hello());
</script><body></html>

函数hello(){return“console.log(\“hello\”);};
document.write(hello());

但是要获得完整的答案,请参阅。您需要它做什么?有时
toString
会被覆盖,这就是为什么最好使用
Function.prototype.toString.call(hello)。然而,几乎没有一个用例是一个好的解决方案,如果你让我们知道更多的话,很可能会有一个更好的解决方案来解决你的实际问题