舉例來說,如果我有這樣的事情:關閉功能的腳本內容轉換爲字符串
function hello() {console.log("hello")}
我希望能夠使Java腳本函數會返回一個字符串值:
"console.log("hello");"
有沒有辦法用普通的javascript做到這一點?
舉例來說,如果我有這樣的事情:關閉功能的腳本內容轉換爲字符串
function hello() {console.log("hello")}
我希望能夠使Java腳本函數會返回一個字符串值:
"console.log("hello");"
有沒有辦法用普通的javascript做到這一點?
您可以通過調用函數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);
如果你hello.toString()
它將輸出"function hello() {console.log("hello")}"
,但看到[你的問題重複](http://stackoverflow.com/questions/14885995/how-to-get-a-functionss-body-as-string)的完整答案 –
其他人已經提供了正確的答案。只需引用它:
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>
它不會是一個字符串,雖然 – Pixeladed
您需要什麼? – Bergi
有時'toString'被覆蓋,這就是爲什麼最好使用'Function.prototype.toString.call(hello);'。但是,幾乎沒有使用情況下這是一個很好的解決方案,如果您讓我們更多地瞭解它,很可能有更好的解決方案解決您的實際問題。 –