jquery anonymous function declaration meanings

后端 未结 2 1609
囚心锁ツ
囚心锁ツ 2021-01-30 06:02

Are the following assumptions accurate?

1) execute immediately

(function(){
})();

2) execute on document ready

$(docume         


        
相关标签:
2条回答
  • 2021-01-30 06:10

    Here's the #4 you were looking for:

    jQuery(function ($) {
    });
    

    It will run on document.ready, within a namespace, and with jQuery defined as $.

    0 讨论(0)
  • 2021-01-30 06:17

    Yes your definitions are correct, for the first 3 :)

    Though, unless you need a closure, a statement will execute immediately, no reason to wrap it like #1 has (there are certainly plenty of valid times you need a closure, just noting if you don't...it's superfluous).

    Number 4 however is not correct, (function($) { })(jQuery); is not tied to any event, it's just a closure so that $ === jQuery inside of it, so you can use the $ shortcut:

    (function($) { 
      //You may use $ here instead of jQuery and it'll work...even if $ means
      //something else outside of this closure, another library shortcut for example
    })(jQuery);
    
    0 讨论(0)
提交回复
热议问题