»
S
I
D
E
B
A
R
«
Passing/calling a function by its name in JavaScript
September 14th, 2009 by admin

Today, I needed some code that would allow me to pass a function name as a parameter, and then call that function on the fly. Well, today, I found out something very useful. You can actually pass the function itself into the function, and then use the built in method called apply to call the function.

To help you more easily understand this, I have included an example:

function callMe( useThisFunction, parameter )
{
    useThisFunction.apply( useThisFunction, Array(paramater) );
}

/**************************************************/

function test( outputMe )
{
    alert(outputMe);
}

/**************************************************/

document.onload = function()
{
    callMe( test, ‘Look at me, I have been outed!’ );
};

Enjoy!

Nick


One Response

tmallare writes:
September 24th, 2009 at 2:29 am

Nice site!

Leave a Reply

You must be logged in to post a comment.

»  Substance: WordPress   »  Style: Ahren Ahimsa