anpel
anpel

Reputation: 941

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.

Upvotes: 3

Views: 132

Answers (3)

FrancescoMM
FrancescoMM

Reputation: 2960

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();

Upvotes: 2

UTunnels
UTunnels

Reputation: 11

You can use eval.

eval('var '+name+'=function(){alert("hello");};');

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

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();

Upvotes: 8

Related Questions