Passing a function as an argument and using the evaluated functionas an argument

Discussion in 'Javascript' started by User1014, Nov 30, 2006.

  1. User1014

    User1014 Guest

    Since you can pass a function to a ... erm...... function....

    how to you use the result of a function as the argument for another
    function instead of passing the actual function to it.

    i.e.

    function foo2(){}

    function foo(func){}


    foo(foo2);


    This passes foo2 to foo, can I do foo(foo2()) ?

    i.e. is the difference between whether a function is passed or evaluated
    dependent on whether you use "()" after the function name?
     
    User1014, Nov 30, 2006
    #1
    1. Advertising

  2. Re: Passing a function as an argument and using the evaluated function as an argument

    User1014 wrote:
    > Since you can pass a function to a ... erm...... function....
    >
    > how to you use the result of a function as the argument for another
    > function instead of passing the actual function to it.
    >
    > i.e.
    >
    > function foo2(){}
    >
    > function foo(func){}
    >
    >
    > foo(foo2);
    >
    > This passes foo2 to foo, can I do foo(foo2()) ?


    Yes you can do that. An argument to a function call is an expression
    that is evaluated prior to passing the resulting value as the actual
    argument. Functions calls are themselves expressions so they are fine
    in an arguments list.

    Whether the resulting code would be as clear is it could be is another
    question though.

    > i.e. is the difference between whether a function is passed or evaluated
    > dependent on whether you use "()" after the function name?


    Yes, a function name is an identifier and evaluates as a reference to
    the function object. A Parenthesise following a function name (with
    arguments or not) act as an operator that evaluates the Identifier to
    its left to the value of a reference to a function object and then
    operates upon that value by executing the function.

    Whatever expression you provide as an argument is fully evaluated
    before the resulting value is passed as an argument.

    Richard.
     
    Richard Cornford, Nov 30, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steph
    Replies:
    2
    Views:
    1,667
    heislord5
    May 11, 2011
  2. David Isaac
    Replies:
    6
    Views:
    310
    David Isaac
    May 27, 2005
  3. Raghu Kodali
    Replies:
    7
    Views:
    349
  4. Jason
    Replies:
    2
    Views:
    91
    Jason
    Dec 15, 2005
  5. Arturo B
    Replies:
    10
    Views:
    137
Loading...

Share This Page