this永远指向的是所属函数的调用对象,也就是说,this属于某个函数,哪个对象调用了这个函数,this就指向哪个对象;对this的指向一定要注意包含this的函数被谁调用,被window调用则会指向window;
如
this.ele.onclick = this.move;
//move是对象的某个方法,this.ele是对象的一个属性;
此时move方法里的this指向的并不是对象,而是this.ele;
因为实际在move()被调用时是this.ele在调用;
这里相当于把move()方法的引用传递给了this.ele.onclick()方法了,自然move()里的this指向的是this.ele;
所以move方法里的this指向需要注意了
this.ele.onclick = function() {
move();
}
//在这里move是被window调用的,省略了前面的window,所以move里的this指向window;
如何修改指向呢?原则是保证对象的方法中this要指向对象,方法调用是对象实例调用;
对于this.ele.onclick = this.move;
的调用方法要进行包装,用this.ele.onclick = function() {This.move();}
同时必须通过赋值操作This = this;
将This指向对象;如果需要用到this.ele指向的元素,则可以通过传参数给This.move(this);来实现;
整体类似的代码如下所示:
Tab.prototype.init = function() {
var that = this;//把实例对象的引用传递给另一个变量that;
for(var i = 0; i < this.aInput.length; i ++) {
this.aInput[i].index = i;
this.aInput[i].onclick = function() {
that.change(this);
}
}
};
Tab.prototype.change = function(btn) {
for(var i = 0; i < this.aInput.length; i ++ ) {
this.aInput[i].className = '';
this.aDiv[i].style.display = 'none';
}
btn.className = 'active';
this.aDiv[btn.index].style.display = 'block';
};