Dynamic function in Javascript
Posted on: 2012-05-23
In some occasion, calling a dynamic function in Javascript can be useful. This is the case when you have a string that represent the name of the function that you want to execute. One way to do it it to use the EVAL keyword in Javascript. It's not the best way to do it, but it's the more known by developer. It let you evaluate Javascript in a string format. That mean that anything given to that function is executed on the client browser. This open a door to malicious code that could be executed if not well used. This is why, I'll show you a second approach that will not use the EVAL key work to execute dynamic method in Javascript.
First of all, here is an example of code that execute a dynamic function with the EVAL keyword.
function myFunction { alert('Test'); }
var functionName = "myFunction"; //Dynamic builded
var functionParameter = "firstParameter, secondParameter"; //Dynamic parameters
var functionToCall = functionName + "('" + functionParameter + "');";
var ret = eval(functionToCall);
As you can see, we could had some kind of logic to choose the functionName. This could have been generated by the server side or could have been loaded from the database or a Web Service. The dangerous part is that someone could change the functionName to direct Javascript statements that could harm the user.
Second, here is better approach that consist to use the window object to call the method. This, atleast, ensure that we are calling a function and not any Javascript statement. Howerver, it's still possible to be hacked and to executed harmful code.
function myFunction { alert('Test'); }
var functionName = "myFunction"; //Dynamic builded
var functionParameter = "firstParameter, secondParameter"; //Dynamic parameters
var functionToCall = window[functionName];
var ret = functionToCall(functionParameter);
In both case, the important thing is not to EVAL data that has been inputted by the user. The executed dynamic code in Javascript must be generated by the developper that has build the system only.