Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - 我可以获取存储在对象中的函数的字符串化代码吗?(Can I get the stringified code of a function stored in an object?)

If I store a javascript function inside an Object like this :

(如果我将javascript函数存储在这样的Object中:)

 jsObject = { TestFuntion1 : function(){ var x = 1; return x; }, TestFunction2 : function(){ console.log("Hello World"); } } 

Can I get the content of these function as a string ?

(我能否以字符串形式获取这些函数的内容?)

var x = 1; return x;    /*OR*/   console.log("Hello World");

I tried playing with the 'prototype', but nothing seems to return me the content of it.

(我曾尝试过使用“原型”,但似乎没有任何东西可以退还给我。)

Thank you for your help !

(谢谢您的帮助 !)

  ask by Tryall Allombria translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be done with the toString() function followed by a little parsing to make it look as desired:

(这可以通过toString()函数完成,然后进行一些解析以使其看起来像期望的那样:)

//convert to string
var str = jsObject.TestFuntion1.toString();

//parse to make it look like you want:
str = str.substring(0, str.length - 1).replace("function(){", "").trim().replace(/
/g, "").replace(/;s+/, "; ");

//check the result
console.log(str);//"var x = 1; return x;"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...