Anonymous function in script after all libraries

Just wondering if there is any benefit to using style: (function() { <code> })();

in your script files going through library scripts. This is basically where the logic goes to set up event listeners and other initialization logic.
For example:

<script>
(function() {
     $('div').on('click', 'a', function() {
          alert('click');
     });
})();
</script>

      

vs

<script>
     $('div').on('click', 'a', function() {
          alert('click');
     });
</script>

      

+3


source to share


3 answers


The point of a self-executing anonymous function in this case is to avoid defining global functions or variables when a true global is not needed. Since your example has none, it is unnecessary in this case.

The self-tuning anonymous function provides a private closure for you to define whatever you want, and it is isolated from the outside world. It does not conflict with any external code, and external code cannot directly access functions and variables inside the closure.



As for your question as to whether this is standard practice, it really depends on you. I personally think this is a good idea, because then you can freely define helper functions or a random global without touching the real global space. If you are using $(document).ready(fn)

, you already have a closure around your init code, so you are already tuned in for that. If not, it's up to you. I personally think this is a good idea and I see a slight downside to making it standard practice. You should of course keep in mind that if you want a true global variable or function, you will need to define it on the object window

so that it is available outside of your closure.

+2


source


No, the first one is just additional code.



Now there might be a case where the former will hold global blocks.

+2


source


You need to use jQuery (document) .ready (function () {...}); model for setting event listeners, otherwise um ... well jQuery won't be ready.

0


source







All Articles