As other have mentioned, this is done with property accessor operators - "[" and "]". What matters in this case is how this function is declared and where it's being referenced from.
If it is declared globally (i.e. in the global scope, as function declaration or function expression), or assigned to a property of a Global Object at some point, then it is possible to access it as a property of a Global Object. In 3rd. edition of ECMAScript-262, one can access Global Object with an expression such as:
(function(){ return this; })();
// or just `this` when in global scope
(Note that in browsers, Global Object is usually the same object as the one referenced by global window
, although it doesn't have to be that way).
So you would access global function as:
var globalObj = (function(){ return this; })();
globalObj['your_func'];
// or via `window`
window['your_func'];
The problem usually arises when function is declared locally – that is in another function body:
(function(){
function your_func(){};
// how to access `your_func` here?
});
The problem is essentially due to the fact that while it is possible to access Global Object (as in previous example), it's not possible to access function's Variable Object (i.e. object used as a "base" for variable and function declaration in function code).
You can certainly use eval
in cases like that but it's most definitely a wrong approach to the problem. A much easier, more compatible and runtime-efficient way is to attach function as a property of some local object:
(function(){
...
function your_func(){}
var funcs = { your_func: your_func };
...
})();
then use the very same brackets to access a property – property referencing function in question:
funcs['your_func'];