What is the benefit of wrapping a jquery function in a closure?

后端 未结 3 2070
鱼传尺愫
鱼传尺愫 2021-01-05 03:25

Hi I\'ve been busy trying to take my knowledge of JQuery to the next level, So far I think I\'ve understood everything but as I\'ve ventured onto more advanced tutorials I\'

3条回答
  •  太阳男子
    2021-01-05 04:17

    If you are writing a plugin, use

    (function($) {
      //stuff that uses the jquery lib using $
    })(jQuery);
    

    This is equivalent to

    var __myf = function($) {
      //stuff that uses the jquery lib using $
    };
    __myf(jQuery);
    

    If you are writing page code, use

    jQuery(function($) {
      //stuff that uses the jquery lib using $
    });
    

    Here, jQuery will invoke your function when it's ready to (when the document is loaded), and will pass itself as the first argument to your function.

提交回复
热议问题