title: JS Variable Scope
body: <p>Variable scope in JS is confusing the hell out of me. In the following code, if I use the <code>setClient</code> public method to set a <code>clientID</code> I can then access the value from inside the track method using the <code>getClient</code> method. I cannot, however, access the value of the private member 'version' this way (or any other private member). I had assumed that var <code>_this = this</code> would create a closure of some sort allowing access to the scope of the Container function.</p>
  <p>And now I'm confused. I realise this is probably really simple though, so I thought I'd ask here. Where on earth have a grasped the wrong end of the stick?</p>
  <pre><code>function Container()
  {
      // private members
      var version = '0.1';
      var CID = false;
      var _this = this;
      
      // public members
      this.getVersion = function() { return _this.version; }
      this.getClient = function() { return _this.CID; }
      this.setClient = function(CID) { _this.CID = CID; }
      
      // private methods
      this.getQS = function() { return _this.version; }
      
      // public methods
      this.track = function()
      {
          if (_this.CID)
          {
              var date = new Date();
              
              data = 
              {
                  cid: _this.getClient(),
                  sw: screen.width ? screen.width : false,
                  sh: screen.height ? screen.height : false,
                  d: date.getTime()
              }
              
              qs = '';
              
              for (p in data) { qs += p+'~'+data[p]+'-'; }
              
              var elHd = document.getElementsByTagName(&quot;head&quot;)[0];         
              var elScr = document.createElement('script');
  
              elScr.type = 'text/javascript';
              elScr.src = 'http://example.org/'+qs+
                              'version-'+_this.getVersion();
              
              elHd.appendChild(elScr);
          }
          else
          {
              alert('no client ID');
          }
      }
  }
  </code></pre>