Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anonymous function in script after all libraries

Just wondering if there's any benefit to using the style: (function() { <code> })(); in your script files proceeding the library scripts. Basically the place where logic goes for setting up the event listeners and other initialization logic.
So for example:

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

v.s.

<script>
     $('div').on('click', 'a', function() {
          alert('click');
     });
</script>
like image 917
paul smith Avatar asked Mar 17 '26 10:03

paul smith


1 Answers

The point of the 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 neither, it is not needed in this case.

The self executing anonymous function provides a private closure for you to define anything you want and it is isolated from the outside world. It wont cause conflicts with any outside code and outside code cannot directly access the functions and variables inside the closure.

As to your question about whether it's a standard practice, that's really up to you. I personally think it's a good idea because then you are free to define helper functions or an occasional global without touching the actual global space. If you're using $(document).ready(fn), then you already have a closure around your init code so you're already set in that regard. If not, it's up to you. I personally think it's a good idea and see little downside to making it a standard practice. You do, of course, have to remember that if you need a true global variable or function, then you will have to define it on the window object so it's available outside your closure.

like image 72
jfriend00 Avatar answered Mar 20 '26 02:03

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!