情景:
function xilou(){
this.name="xilou";
this.sex="男";
this.num=0;
}
xilou.prototype.count=function(){
this.num+=1;
alert(this.sex+this.num+this.name);
alert(this.count)
var self=this;
//setTimeout(function(){self.count();},1000); //D:正确
//setTimeout(\'self.count()\',1000)// can\'t do it
}
var x=new xilou();
x.count();
问题:
为什么第一种正确,第二种不行,第二种的self不就相当于x吗?
解析:
这是有关於javascript变量作用域的问题,setTimeout的作用域是window
针对与你现在这个具体的代码说明下
setTimeout(function(){self.count();},1000); //D:正确
你在此生成了个匿名函数,在这个函数调用时会逐层的找self这个玩意,由於javascript对作用域的解释,故而能找到你要的self
setTimeout(\'self.count()\',1000)
此处给setTimeout的是字符串,其作用域是window,故而找不到self
倒计时器:
var Countdown = function(Selector,count,callback){
this.timeout =count;
this.modifyObj = $(Selector);
this.callback = callback;
};
Countdown.prototype.Count = function ()
{
if(this.timeout<0){
this.callback();
return;
}
this.modifyObj.text(this.timeout);
this.timeout--;
var self =this;
setTimeout(function(){self.Count()},1000);
};
倒计时器的使用:
var countdown = new Countdown(\'#counttext\',20,function(){
layer.close(index);
});
countdown.Count();