使用参数JS打印功能代码

Olo*_*oji 10 javascript function

我想获取所有功能代码(带参数)并在div.code中打印

html文件

<script src='script.js'></script>
...
<input type=text value='text' id='my_input'>
<div class='code'></div>
<script>
   document.querySelectorAll('div.code')[0].innerHTML=func(document.getElementById('my_input'));
</script>
Run Code Online (Sandbox Code Playgroud)

的script.js

function func(param){
console.log(param);
}
Run Code Online (Sandbox Code Playgroud)

所以在div.code中它应该是

"function func(text){
    console.log(text)
    }"
Run Code Online (Sandbox Code Playgroud)

我应该用它做什么?我试图使用toString,toSource,JSON.stringify但它不起作用

m.a*_*icz 8

您应该使用String()从功能代码创建字符串

function f(param) {
    console.log(param);
}

alert( String(f) );
// ...innerHTML = String(f);
Run Code Online (Sandbox Code Playgroud)

如果要替换param输入,可以String(f)对字符串进行结果操作

alert( String(f).replace(/param/g, 'text') );
// ...innerHTML = String(f).replace(/param/g, document.getElementById('my_input'));
Run Code Online (Sandbox Code Playgroud)

看看这个jsFiddle示例


另请在此处阅读有关String()函数的更多信息