What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

后端 未结 8 1798
轮回少年
轮回少年 2020-11-22 02:02

I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.

(f         


        
8条回答
  •  执念已碎
    2020-11-22 02:39

    In addition to keeping the variables local, one very handy use is when writing a library using a global variable, you can give it a shorter variable name to use within the library. It's often used in writing jQuery plugins, since jQuery allows you to disable the $ variable pointing to jQuery, using jQuery.noConflict(). In case it is disabled, your code can still use $ and not break if you just do:

    (function($) { ...code...})(jQuery);
    

提交回复
热议问题