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

后端 未结 3 2086
鱼传尺愫
鱼传尺愫 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 03:51

    It's a self invoking anonymous function (an un-named function that is declared and immediately executed) that takes one argument that gets assigned to the parameter $. The value passed in for the argument is jQuery, the jQuery function.

    This is done so that the shorthand $ can be used inside the scope of the function to mean jQuery. Since all of the code inside of the function is in the scope of the function, it's a nice pattern for self containing the code and not polluting the global namespace.

    It's also a nice pattern for allowing you to use the $ shorthand for jQuery inside of the function - it could be the case that the $ shorthand (window.$) is assigned something else, as can happen if you use multiple libraries on one page. By using the pattern, you can still use $ to reference jQuery object in the function for familiarity and terseness.

提交回复
热议问题