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