2

What are the pros and cons of the following function scopes:

Global Function/Inline JS

<script>
    function funcA() {
        //do something
    }
</script>
<button id="buttA" onclick="funcA();">Click Me</button>

Global Function/Non-inline JS

<script>
    function funcA() {
        //do something
    }
    $(function() {
        $('#buttA').on('click', funcA);
    });
</script>
<button id="buttA">Click Me</button>

Non-global Function/Non-inline JS

<script>
    $(function() {
        $('#buttA').on('click', funcA);
        function funcA() {
            //do something
        }
    });
</script>
<button id="buttA">Click Me</button>

Which combination is better and why?

PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • 1
    Well, using inline event handlers [has some drawbacks](http://stackoverflow.com/a/21975639/218196) and polluting the global namespace (scope) isn't that great either. Leaves only the third option ;) – Felix Kling Jun 01 '14 at 04:26
  • Thanks for your quick response. What is wrong with global functions or variables? – PeterKA Jun 01 '14 at 04:42
  • Maybe have a look at http://stackoverflow.com/q/8862665/218196 – Felix Kling Jun 01 '14 at 04:57

1 Answers1

2

I think the big argument to not use global variables comes with the nature of web collaboration. If you're build a site-wide script, and you have a team of lets say two others working on plugins, you don't want your variables to be overwritten or invoked by your collaborators. Additionally, having people consistently asking you to provide them with a list of your program variables and functions is going to slow everything down.

/* Private namespace */
(function () {

   var sum_1 = 10;
   var sum_2 = 20;

   var myFunction = function (x, y) {
      return x * y;
   };

   myFunction(sum_1, sum_2);

})();
lindsay
  • 972
  • 2
  • 11
  • 21
  • Great point! Thanks! Would you have anything specific to say about the third option, either for or against? – PeterKA Jun 20 '14 at 16:48