Using Self Calling Anonymous Functions and $(document).ready

后端 未结 3 1436
-上瘾入骨i
-上瘾入骨i 2021-02-04 17:50

I just recently learned about self calling anonymous functions. Some snippets of code that I came across used the self calling function along with the $(document).ready. It se

3条回答
  •  盖世英雄少女心
    2021-02-04 18:24

    There's definitely a use case for the first example. If you have other JS libraries/scripts loaded on the same page, there's no guarantee that they aren't overwriting the $ variable. (This is very common when you have Prototype and jQuery on the same page).

    So if Prototype is using $, you would need to use jQuery anytime you wanted to work with jQuery. This can get quite ugly:

    jQuery(function(){
        jQuery('a', '#content').bind('click', function(){
            if(jQuery(this).attr('href') == 'www.google.com')
            {
                alert("This link goes to Google");
                jQuery(this).addClass('clicked'));
            }
        });
    })
    

    Remember, we can't use $ because that is a method from Prototype in the global scope.

    But if you wrapped it inside of this..

    (function($){
        $(function(){
    
            // your code here
    
        });
    })(jQuery);
    

    The $ would actually reference the jQuery library inside while still referring to Prototype on the outside! This can help tidy up your code:

    (function($){
        $(function{}(
            jQuery('a', '#content').bind('click', function(){
                if(jQuery(this).attr('href') == 'www.google.com')
                {
                    alert("This link goes to Google");
                    jQuery(this).addClass('clicked'));
                }
            });
        ));
    })(jQuery);
    

    This is a common pattern with jQuery extensions to ensure that they are always added to the jQuery object, but can be written using $ to keep the code tidy.

提交回复
热议问题