!function ($) { }(window.jQuery) what is this code for?

Possible Duplicate:
What is the purpose of this? (function ($) { //function code here })(jQuery);
What does the exclamation mark do before the function?
negating self invoking function? !function ($) { … }(window.jQuery);

!function ($) {
     $(function() {
            .
            .
            .
    })
}(window.jQuery)

I saw this in a jquery example and was wondering what the !function($){}(window.jQuery) was for. Particularly the exclamation mark was new to me.


Ok I figured it out after doing some research but I will leave the answer in for others.

Basically it's to avoid conflicts with other javascript libraries which also use the dollarsign.

So Jquery advices to use jQuery or window.jQuery instead of the dollar sign . It's usually used in combination with jQuery.noConflict() to make jQuery give up on the $ sign used in other javascript libraries when you mix libraries .

This is actually a way of running a self-executing function that passes in the window.jQuery object and passes it on to the $ sign. This way you can keep using the dollar sign in your code without having to worry about other javascript libraries that could cause a conflict with your code.

Wrapping it up in this function saves yourself from using window.jQuery everywhere to replace the $ sign.

If you execute function () {}() like this it results in a syntax error as it's just a function declaration. The ! turns it into an expression which can be executed.

So basically you can use both for the same purpose.

!function($){}()
(function($){})()

Feel free to modify or complement.

references:

  • What is the purpose of this? (function ($) { //function code here })(jQuery);
  • What does the exclamation mark do before the function?
  • 链接地址: http://www.djcxy.com/p/96904.html

    上一篇: Javascript立即调用函数模式

    下一篇: !函数($){}(window.jQuery)这个代码是什么?