Note that there are some explanatory texts on larger screens.

plurals
  1. POJS Variable Scope
    text
    copied!<p>Variable scope in JS is confusing the hell out of me. In follwing code, if i use the setClient public method to set a clientID i can then access the value from inside the track method using the getClient method. I cannot however access the value of the private member 'version' this way (or any other private member).. i had assumed that var _this = this 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("head")[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>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload