0

例如,如果我有这样的事情:

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

我希望能够在 java 脚本中创建一个返回字符串值的函数:

"console.log("hello");"    

有没有办法用纯javascript做到这一点?

4

3 回答 3

1

如果你这样做hello.toString(),它将输出"function hello() {console.log("hello")}"

于 2013-09-24T15:37:11.457 回答
1

您可以通过调用函数上的方法来获取包括函数声明在内的所有代码toString()。然后,您可以解析此字符串以删除不需要的信息。

像这样的东西:

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);

这是一个工作示例

于 2013-09-24T15:46:32.947 回答
0

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

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>
于 2013-09-24T15:51:32.783 回答