Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Create functions with variable name

Tags:

javascript

I am trying to create some functions based on variable names, something along the lines of:

var functionsToRegister = ["foo","bar"];

var index;
for (index = 0; index < functionsToRegister.length; ++index) {
    var function_name = functionsToRegister[index];

    PART_IM_MISSING = new Function('return alert("hello, world!");');
}

The client code calls specific methods so for example it will call foo()

Please note that I am not working on a website but on a native windows application (SoftOne) that allows some customization options through a javascript engine.

Also there is absolutely no way to change the client code calling the functions.

like image 578
anpel Avatar asked Dec 29 '25 00:12

anpel


1 Answers

You could use the window object, to make a global function.

var functionsToRegister = ["foo", "bar"],
    index,
    function_name;

for (index = 0; index < functionsToRegister.length; ++index) {
    function_name = functionsToRegister[index];
    window[function_name] = new Function('return alert("hello, world!");');
}

foo();
like image 70
Nina Scholz Avatar answered Dec 30 '25 13:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!