日期:2014-05-16  浏览次数:20408 次

关于this的指向问题
代码(部分):

function Butimgbar(imagepre,butpre,speed)
{
this._imagepre = imagepre;
this._butpre = butpre;
this._speed = speed;
this._isrun = false;
this._lastid = 0;
this._usedimg = this._imagepre + " li:eq(";
this._setevent = function(id){
$("#Slide li").mouseover(function(){
$(this._usedimg + id + ")").fadeIn(this._speed);
$(this._usedimg + this._lastid + ")").fadeOut(this._speed);
this._lastid = id;
});
}
}


这里使用到了jquery
问题来了,代码中的"#Slide li"是页面中的一组li
这里是我当时测试,所以直接写了"#Slide li"
问题是,我希望在onmouseover的事件中,能够使用这个对象(Butimgbar)的属性,但是触发时实际的this指向的是<li>标签(应该是吧?)
那么,应该怎么办呢?
------解决方案--------------------
可以这样

function Butimgbar(imagepre,butpre,speed)
{
    var self =this; //保存对象
    this._imagepre = imagepre;
    this._butpre = butpre;
    this._speed = speed;
    this._isrun = false;
    this._lastid = 0;
    this._usedimg = this._imagepre + " li:eq(";
    this._setevent = function(id){
        $("#Slide li").mouseover(function(){
            $(this._usedimg + id + ")").fadeIn(this._speed);
            $(this._usedimg + this._lastid + ")").fadeOut(this._speed);
            this._lastid = id;
            console.log(self);//这里用这个
        });
    }
}

------解决方案--------------------
把this用一个变量保存起来不就行了

function Butimgbar(imagepre,butpre,speed)
{
    this._imagepre = imagepre;
    this._butpre = butpre;
    this._speed = speed;
    this._isrun = false;
    this._lastid = 0;
    this._usedimg = this._imagepre + " li:eq(";
    //声明一个_this变量,用来保存this    
    var _this  = this;
    this._setevent = function(id){
        $("#Slide li").mouseover(function(){
            $(_this._usedimg + id + ")").fadeIn(_this._speed);
            $(_this._usedimg + _this._lastid + ")").fadeOut(_this._speed);
            _this._lastid = id;
        });
    }
}