How can I store functions in an array with named properties, so I can call like
FunctionArray["DoThis"]
or even
Function
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]()
Basically, a function is a special type of object in JavaScript. And in JavaScript, in array you can store anything (not necessarily of the same type). So going by this, yes!, you can store a function, object, and primitive values in an array in JavaScript:
var arr = ["Hello", true, false, 1, {name: "Arshad"}, function(){}]
And you can mix the object and function to make the named function like:
{ callBythisname: function(){ .... }}
You can store this object in an array as well:
var arr = [{ callBythisname: function(){ .... }}];
If you want to call it, call like:
arr[0].callBythisname();
You even can use a function as the name of the property:
var func = function(a, b){alert(a+b)};
var obj = {};
obj[func] = 2;
You can actually do that. Just declare it outside the array, like so...
const your_function = function(){ console.log("I am your function") }
const group = [0, "lizard", false, your_function()]
group[3]
You may also change where it's called, if you want to...
const your_function = function(){ console.log("I am your function") }
const group = [0, "lizard", false, your_function]
group[3]()
Functions were named wrong :/ sry
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 give it a try here.
You can access an object's properties through its name (x["A"]). If you want to assign indexes (0 = "A") you have to do this, and here is an 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