Function name based on a var

Hello,

I’m in the following situation (simplified for the sake of clarity):


function foo(param,functionName) {
  var result = functionName(param);
  return result;
}

As you can see, I’m trying to call a function from inside another function, the name from the child function being passed as a parameter to the parent function.

Can JS do that? It’s pretty straightforward with PHP, but I can’t find a way to do it with javascript.

:slight_smile:

Exactly as you described. I hope you weren’t passing the function name as a string.

function showParam( p )
{
  alert( p );
}

function foo(param,functionName) {
  var result = functionName(param);
  return result;
}

foo( "Works", showParam );

It’s even more straight forward in javascript. Functions are just objects, like everything else in javascript. Defining a function simply assigns its code to a variable in the local scope, usually the window object. You don’t have to pass the function’s name as an argument to another function, you can pass the function itself.


function bar () {
  alert('Hello');
}

function foo ( func ) {
  func();
  alert( 'World' );
}

foo(bar); // alerts 'Hello', then 'World';

:tup: