Call user func with function name in variable

Discussion in 'JavaScript' started by rodney88, Mar 8, 2007.

  1. #1
    I have the name of a function in a variable - how can I call this function?

    In PHP I'd use
    call_user_func($funcName);
    PHP:
    but I don't know enough javascript.. any help is much appreciated.

    Thanks!
     
    rodney88, Mar 8, 2007 IP
  2. php_daemon

    php_daemon Active Member

    Messages:
    34
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    95
    #2
    
    <script type="text/javascript">
    function foo(){
      alert('bar');
    }
    var f='foo';
    eval(f+'()');
    </script>
    
    HTML:
     
    php_daemon, Mar 8, 2007 IP
    rodney88 likes this.
  3. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Perfect! Thanks for the fast reply.. eval was just what I needed.
     
    rodney88, Mar 8, 2007 IP
  4. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #4
    Aragorn, Mar 8, 2007 IP
  5. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks but that way doesn't work:
    Error: func.call is not a function

    Where func is the variable holding the function name. eval(func+'()') works fine though.
     
    rodney88, Mar 8, 2007 IP
  6. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #6
    func should not be a variable. It should be the function name itself

    
    function foo(var1, var2, var3){
    
    }
    foo.call(thisObj, var1, var2, var3)
    
    
    Code (markup):
    The first variable is the object to be used as the current object, if you are using OOP.
     
    Aragorn, Mar 8, 2007 IP