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.
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?
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');
}
}
}