SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    function name based on a var

    Hello,

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

    Code JavaScript:
    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.


  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Exactly as you described. I hope you weren't passing the function name as a string.

    Code:
    function showParam( p )
    {
      alert( p );   
    }
    
    function foo(param,functionName) {
      var result = functionName(param);
      return result;
    }
    
    foo( "Works", showParam );
    Tab-indentation is a crime against humanity.

  3. #3
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,026
    Mentioned
    64 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Hello,

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

    Code JavaScript:
    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.

    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.

    Code Javascript:
    function bar () {
      alert('Hello');
    }
     
    function foo ( func ) {
      func();
      alert( 'World' );
    }
     
    foo(bar); // alerts 'Hello', then 'World';

  4. #4
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •