Reconstruct and execute javascript functions dynamically

In some scenarios , we have to reconstruct and execute javascript functions dynamically.

//function name to be reconstruct
 function add(a,b) {
 console.log("Result is : " ,a + b);
 }

//regular expression for converting the source code 
 let regExp = /\((.*)\).*\{([\s\S]*)\}/m;
 let sourceCodeParts = regExp.exec(add.toString());
 var functions = {};
 functions["add"] = new Function(sourceCodeParts[1], sourceCodeParts[2]);

//execute the function
functions["add"].apply(null, [8, 2]);
 

 

Output : Result is : 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s