I’m currently trying to teach myself more about javascript, and I find myself stumbling over the syntax for passing a method as an argument to another method call. Say you have two functions like these:
function FirstFunction()
{
DoesSomething();
}
function SecondFunction(func)
{
func();
}
In actually passing the FirstFunction to the SecondFunction, I seem to see a wild variety of variations on doing so:
SecondFunction(FirstFunction);
or
SecondFunction("FirstFunction()");
or sometimes, if FirstFunction was defined as follows:
var thisisafunction = function FirstFunction()
{
DoesSomething();
}
SecondFunction(thisisafunction);
I’m guessing there’s no “one right way” to do this, so when is it appropriate to use each way of passing a function? Is it better to use one way over another in a certain situation?
Passing a string is always bad. It only works with functions like setTimeout which automatically
eval()strings and it’s bad since it runs in the global context.If you just want to pass a plain function without creating a closure or passing arguments, passing the function without
()is fine:If you need to pass arguments or want a closure so you can access some non-global variables inside that function, use an anonymous function:
Of course you can also assign the function to a variable first:
While
var cb = function someName() {};is valid, I’d recommend against giving your function expressions names – it’s not supported by all browsers. The only advantage is having a function name in debuggers anyway…