How can I store functions in an Array with named properties, so I can call like
FunctionArray["DoThis"]
or even
FunctionArray[integer]
Note: I do not wish to use eval
.
How can I store functions in an Array with named properties, so I can call like
FunctionArray["DoThis"]
or even
FunctionArray[integer]
Note: I do not wish to use eval
.
You want an object literal, not an array.
>>> x = { 'dothis': function() { alert('hi'); } };
Object
>>> x['dothis']()
You can also dynamically invoke
>>> y = 'dothis';
>>> x[y]()
Static/hard coded invocation:
>>> x.dothis()
If you do want an array though:
>>> x = [function(){alert('hi');}][0]()
The important thing to remember is that functions are first class objects in JavaScript. So you can pass them around as parameters, use them as object values and so on. Value(s) in an array are just one example of that.
Note that we are not storing the functions in an array although we can do that and access them with a numeric index. We are storing them in a regular object keyed by the name we want to access that function with.
var functions = {
blah: function() { alert("blah"); },
foo: function() { console.log("foo"); }
};
call as
functions.blah();
or
functions["blah"]();
You can store things directly in an array, but as an object, for example:
var Functions = { DoThis: function() { alert("do this"); } };
Functions['DoThis'](); //alerts "do this"
Functions.DoThis() //alerts "do this"
You can access a object's properties through it's name (x["A"]), if you want to assign indexes (0 = "A") you have to do this, here is a example. (I'm not sure if the for
loop will work on any browser, I've tested on Firefox, but you can get the idea)
var x = {};
x.A = function() { alert("func 1"); };
x.B = function() { alert("func 2"); };
var i = 0;
for (a in x)
{
x[i] = x[a];
++i;
}
x[0](); // func 1
x[1](); // func 2
x["A"](); // func 1
x["B"](); // func 2