Dynamic naming and implementation of javascript function body

For simplicity, I included a script that dynamically calls a function by name:

var foo = "hello"; var bar = "world"; var function_name = "say_" + foo + bar; // Since its name is being dynamically generated, always ensure your function actually exists if (typeof(window[function_name]) === "function") { window[function_name](" World!"); } else { throw("Error. Function " + function_name + " does not exist."); } function say_helloworld(the_word) { alert("Hello " + the_word); } 

But the say_helloworld function say_helloworld written statically. I would like something like:

 var function_implementation = 'function say_'+foo+bar+ '(the_world){alert("Hello " + the_world);}'; eval(function_implementation); 

but without using eval (). There's an even uglier approach: making an AJAX call to get a function.

Do you see a better approach?

+4
source share
3 answers

You can use the built-in function expression:

 window['say_'+foo+bar]= function(the_world) { alert('Hello '+the_world); }; 

However, there is almost never a good reason to use dynamically called variables. Instead, save the functions in a separate search object:

 var says= { helloworld: function(the_world) { alert('Hello '+the_world); }, somethingelse: function(otherthing) { alert('Something else with '+otherthing); } }; says[somevar]('potatoes'); 
+5
source

If you want to dynamically generate your function without eval , you can use the constructor

 Function([arg1[, arg2[, ... argN]],] functionBody) 

That way you can do things like

 var func = new Function('message', 'alert("Hello, " + message);') func('world!'); 

See MDC for details.

Greetings

Note I had never used this approach before, and I had never used the Function () constructor before. Therefore, I do not know if there may be other shortcomings.

+1
source

You can use a timeout that your code will interpret, but it can use eval internally, so I'm not sure if you want this.

 fText = 'function test(a){alert(a);}'; setTimeout(fText,0); 

but you need to allow a few milliseconds before calling it.

+1
source

All Articles