anpel anpel - 2 months ago 7
Javascript Question

Javascript - Create functions with variable name

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.

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

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

    this[function_name]=function() {
        return alert("hello, world!");
    }
}

This will add functions foo and bar to the this object (or you can use any object like window),

but I guess you don't want n identical functions.. so maybe:

var functionsToRegister = {
    'foo':function() {return alert("hello, foo!");},
    "bar":function() {return alert("hello, bar!");},
};


var index;
for (index in functionsToRegister) if(functionsToRegister.hasOwnProperty(index)) {
    var function_name = index;
    var function_code = functionsToRegister[index];


    this[function_name]=function_code;
}


this['foo']();
this.bar();

foo();