title: JavaScript, accessing a global variable through a function
body: <p>Before I specify what I am struggling with, let me show you my JavaScript codes.</p>
  
  <pre><code>var gVar = 0;
  
  $("#plus").click(function(e) {
      e.preventDefault();
      gVar = gVar + 1;
      alert(gVar);
  });
  
  $("#minus").click(function(e) {
      e.preventDefault();
      gVar = gVar + 1;
      alert(gVar);
  });
  </code></pre>
  
  <p>In the code above, I first set a global variable 'gVar' that holds a integer value of zero. Whenever I click a button whose ID is "plus", the value of the global variable 'gVar' is going to increment by 1, which will be printed out in a browser's dialogue box.</p>
  
  <p>The same thing will happen for the button whose ID is "minus" except that the value of 'gVar' is going to decrement by 1.</p>
  
  <p>In my attempt to tidy up the code above, I created a function separately, which will be called whenever I click the two buttons. Here are the code.</p>
  
  <pre><code>var gVar = 0;
  
  var weird = function (button, Var, num1) {
      $(button).click(function(e){
          e.preventDefault();
          Var = Var + num1;
          alert(Var);
      });
  };
  
  weird("#plus", gVar, 1);
  weird("#minus", gVar, -1);
  </code></pre>
  
  <p>When I run this code, the value of 'gVar' never changes and always stays '0'.</p>
  
  <p>I think I vaguely know what the issue here is, but not entirely sure what is causing this problem. Any input will greatly be appreciated to clarify this issue for me.</p>
  
  <p>Also, I am curious as to if there is any way to create a function to achieve the same effect instead of writing a similar set of code twice for the two different click events.</p>