簡體   English   中英

使用參數JS打印功能代碼

[英]Print function code with parameters JS

我想獲取所有功能代碼(帶參數)並在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>

的script.js

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

所以在div.code中它應該是

"function func(text){
    console.log(text)
    }"

我應該用它做什么? 我試圖使用toString,toSource,JSON.stringify但它不起作用

您應該使用String()從函數代碼創建字符串

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

alert( String(f) );
// ...innerHTML = String(f);

如果要用輸入替換param ,可以在String(f)結果上操作字符串

alert( String(f).replace(/param/g, 'text') );
// ...innerHTML = String(f).replace(/param/g, document.getElementById('my_input'));

看看這個jsFiddle示例


另請在此處閱讀有關String()函數的更多信息

您可以使用 :

 f.toString();

 function f(a, b, c) { } document.write(f.toString().replace(/\\n/g, "<br>")); 

我建議調用Function Object的vanilla toString函數來對你的函數進行字符串化,如下所示:

Function.prototype.toString.call(yourFunctionHere);
//or just use it directly on your function, if you're not going to modify the prototype
yourFunction.toString();

這會打印您提到的功能。

如果您想在之后替換值,可以將replace與regex結合使用。

像這樣:

function myFunction(param1){
    alert(param1);
}

Function.prototype.toString.call(myFunction).replace(new RegExp('param1', 'g'), 'theParam');

這將為您提供以下內容:

"function myFunction(theParam){
    alert(theParam);
 }"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM