1
function f1 () {
    console.log('f1')
}

var s = 'f1'

runLocalFunctionByName(s)

Is this possible at all to write runLocalFunctionByName() or just call f1 without typing f1 in the source code, but using a variable holding its name? I mean without modifying f1 into a method, that answer is obvious: just make myobj.f1 = function or declare it globally like f1= function(). I am talking about normal local functions declared with function keyword only, not as vars, global vars or some other object property.

exebook
  • 32,014
  • 33
  • 141
  • 226
  • 5
    Why do you need to do this? I suspect this is an XY problem, and there's a better way to solve it. – Barmar Dec 24 '15 at 11:43
  • Somewhat related: http://stackoverflow.com/questions/2146173/how-to-get-local-variable-by-its-name-in-js, http://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript. –  Dec 24 '15 at 13:24
  • `f1` is not a local function here--by "local" do you mean that it is defined inside some other function? –  Dec 24 '15 at 13:32

3 Answers3

4

Not without the use of eval, which is evil (when used for this purpose for sure!).

Global functions could be called as attributes of the window object, but if they are in a local/closure scope that's not possible.

If you need to call functions by name, the only proper solution is storing them as attributes on an object, and then using obj[s]() for calling them.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

One way of doing this is by using the instantiating a Function object.

var runLocalFunctionByName = function(fName) { 
    return (new Function('','return '+fName+'();'))(); 
};

Calling runLocalFunctionByName with a name of a function will now return the output of the named function.

EDIT

In case of local functions, the scope has to be mentioned, so we can modify the code, such that:

var runLocalFunctionByName = function(fName, scope) { 
    return (new Function('','return '+(scope?scope:'this')+'.'+fName+'();'))(); 
};
Soubhik Mondal
  • 2,666
  • 1
  • 13
  • 19
0

You can't access a local function outside its scope until unless you assign it to a variable having an accessible scope. MDN: A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit)

mak
  • 71
  • 3
  • 1
    He's not worried about scoping. He's trying to call a function when what he has is its name in string form. –  Dec 24 '15 at 13:10