1

So, we should all know about the jQuery document-ready handler:

$(function () {
  // stuff here
});

So basically, if the first parameter for the $ function is a function, then we run it on document startup, right?

Then why won't this work?

$(foo());
Lucas
  • 15,579
  • 27
  • 98
  • 170

5 Answers5

9

When you type $(foo()); you are actually calling foo and pass the result to $. If you want to use foo as a callback, you need to type $(foo).

Constantinius
  • 30,633
  • 7
  • 68
  • 82
7

Because the result from foo() isn't a function.

Use: $(foo);

IvanL
  • 2,375
  • 1
  • 22
  • 37
4

Here you go.

function foo() {
  return function() {
    console.log("Hello World");
  } 
}

$(foo());

Now it works. (See what I did there?)

tylerl
  • 28,220
  • 12
  • 76
  • 108
  • Clever, but I struggle to conceive of a situation where it would be practical. Have a +1 anyway. – TRiG Sep 03 '14 at 16:22
1

foo is named function and its not anonymous. So it needs to be used like $(foo);

Check this out

var functionName = function() {} vs function functionName() {}

Community
  • 1
  • 1
Murali Murugesan
  • 21,303
  • 16
  • 65
  • 114
  • I don't see how that's relevant. The problem is that the function needs to be passed instead of the function's result. Whether it's a named function makes no difference. –  Oct 03 '12 at 09:08
1

First, you'll need to know that the first parameter of $ isn't (always) a function. When diving in the jQuery source code, you'll find this function is called:

init: function( selector, context, rootjQuery ) {

Which handles the following (in order):

// Handle $(""), $(null), or $(undefined)
// Handle $(DOMElement)
// The body element only exists once, optimize finding it
// Handle HTML strings (tags, id's etc.)
// HANDLE: $(function)
// Shortcut for document ready

Your question is about the last part, which has the following code:

// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
    return rootjQuery.ready( selector );
}

Here you'll see that jQuery checks if the selector is a function. In your case, it isn't: Youre calling a function, not actually passing a function. When the result from foo is a function, it can work.

You can also change it to this:

var foo = function() {
   // do your stuff
};

$(foo);
MarcoK
  • 5,952
  • 2
  • 26
  • 40