看一个例子
$('#conten').click(function(){
//this是被点击的#conten
var that =this;
$('.conten').each(function(){
//this是.conten循环中当前的对象
//that仍是刚才被点击我的#conten
})
})
this对象在程序中随时会改变,而var that = this之后,that不会改变,仍然指向之前的this,这样就不会找不到原来的对象
tab.prototype.init = function(){
for(var i=0,len =this.span.length;i<len;i++){
var that = this;
that.span[i].index =i;
that.span[i].onclick = function(){
that.show(this.index);
}
}
this.show(1);
}
这个例子中,如果将that.show(this.index) 改为 this.show(this.index),此时 this.show中this指向that.span[i],此时会因为找不到that.span[i]而报错。而改成that.show(this,index),此时,that因为前面申明 var that =this,that指向外层。
理解尚不到位我再查查资料。。。。。。