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

U

User1014

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?
 
R

Richard Cornford

User1014 said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top