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
  • 16,930
  • 31
  • 110
  • 182

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
  • 34,183
  • 8
  • 77
  • 85
7

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

Use: $(foo);

IvanL
  • 2,475
  • 1
  • 26
  • 39
4

Here you go.

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

$(foo());

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

tylerl
  • 30,197
  • 13
  • 80
  • 113
  • 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
  • 22,423
  • 17
  • 73
  • 120
  • 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
  • 6,090
  • 2
  • 28
  • 40