Search code examples
jqueryjquery-uijquery-selectors

What does jQuery(function($) { ... }) means?


I know in jQuery, $(callback) is the same as jQuery(callback) which has the same effect as $(document).ready().

How about

jQuery(function($) {

 });

Can some one explain to me what does this kind of function mean?

What does it do?

what is the difference between this one and $(callback)??

what is the difference between this one and $(function())??


Solution

  • jQuery(function($) {
    
    });
    

    is the safest version of all three. It makes $ the local variable and thus gracefully avoids the conflicts with any other variables which possibly use $ symbol.

    I think it was also added fairly recently, don't remember seeing it before.

    These function all do the same things - execute some code when DOM is ready. $(document).ready(function(){}) is the original one, and it matches the underlying javascript API.

    "$" and "jQuery" which accept function as an arguments were created as shortcuts to avoid repeating such a common construct. Accepting a function which accepts $ as its first argument is a further syntax sugar - now you get convenience of the closures without the need to do it yourself.