title: How to make a global function in JQuery?
body: <p>I'm trying to offload common functions to a separate functions.js file in order to clean things up. I've managed success in making the global functions work, but there's some inconsistency in the way that I need to write and call the function that is confusing me.</p>
  
  <p>One of my global functions:</p>
  
  <pre><code>$.getTld = function() {
      var tld = document.location.hostname.split('.').pop();
      return tld;
  };
  </code></pre>
  
  <p>I can call it like this from another JS file:</p>
  
  <pre><code>$.setPersonaCookie = function(name, value, days) {
      $.cookie(name, value, {
          expires: days, // Expires in 360 days
          path: '/', // Is on the default path
          domain: 'mydomain.' + $.getTld(), // The value of the domain attribute of the cookie
          secure: $.getProtocol() // set secure cookies - setting in htaccess
      });
      return;
  };
  </code></pre>
  
  <p>In my same functions.js file I've set up another function in the same way as I did with the $.getTld function:</p>
  
  <pre><code>$.getQueryVariable = function(name, url) {
      if (!url) url = location.href;
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&amp;]"+name+"=([^&amp;#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( url );
      return results == null ? null : results[1];
  };
  </code></pre>
  
  <p>And I'm calling the function like this:</p>
  
  <pre><code>$(document).getQueryVariable('q');
  </code></pre>
  
  <p>But, I get a console error indicating that $.getQueryVariable is not defined. In order to make it work, I have written the function like this instead:</p>
  
  <pre><code>$.fn.getQueryVariable = function(name, url) {...};
  </code></pre>
  
  <p>When written this way, I can successfully call the function.</p>
  
  <p>So, why do I need to add the extra .fn to the getQueryVariable function to make this work as a global function?</p>