Now, I usually call a function (that requires no arguments) with () like this:
myFunction(); //there's empty parens
Except in jQuery calls where I can get away with:
$('#foo').bind('click', myFunction); //no parens
Fine. But recently I saw this comment here on SO:
“Consider using setTimeout(monitor, 100); instead of setTimeout('monitor()', 100);. Eval is evil :)”
Yikes! Are we really eval()-ing a string here? I guess I don’t really understand the significance and implications of ‘calling’ a function. What are the real rules about calling and referring to functions?
In JavaScript functions are first-class objects. That means you can pass functions around as parameters to a function, or treat them as variables in general.
Let’s say we are talking about a function
hello,When we simply write
we are referring to the function which doesn’t execute it’s contents. But when we add the parens
()after the function name,then we are actually calling the function which will alert “yo” on the screen.
The
bindmethod in jQuery accepts the type of event (string) and a function as its arguments. In your example, you are passing the type – “click” and the actual function as an argument.Have you seen Inception? Consider this contrived example which might make things clearer. Since functions are first-class objects in JavaScript, we can pass and return a function from within a function. So let’s create a function that returns a function when invoked, and the returned function also returns another function when invoked.
Here
realityis a function,reality()is a function, andreality()()is a function as well. Howeverreality()()()is not a function, but simplyundefinedas we are not returning a function (we aren’t returning anything) from the innermost function.So for the
realityfunction example, you could have passed any of the following to jQuery’s bind.