【发布时间】:2009-03-23 19:49:03
【问题描述】:
JS 中的变量范围让我很困惑。在下面的代码中,如果我使用setClient 公共方法设置clientID,然后我可以使用getClient 方法从track 方法内部访问该值。但是,我不能以这种方式(或任何其他私有成员)访问私有成员“版本”的值。我曾假设 var _this = this 会创建某种闭包,允许访问 Container 函数的范围。
现在我很困惑。我意识到这可能很简单,所以我想我会在这里问。到底哪里抓错了大棒?
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');
}
}
}
【问题讨论】:
标签: javascript scope