代码(部分):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>标签(应该是吧?)
那么,应该怎么办呢?

解决方案 »

  1.   

    可以这样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);//这里用这个
            });
        }
    }
      

  2.   

    把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;
            });
        }
    }
      

  3.   

    你先搞明白this的作用域就知道为什么会是这样了;this的作用域只是在当前的函数有效;
    “在onmouseover的事件中,能够使用这个对象(Butimgbar)的属性”最直接有效的方法就是在外面定义个参数来存放Butimgbar对象,然后你在onmouseover的事件中就可以用这个参数。也就是3楼那样
      

  4.   


    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){
            var me = this;
            $("#Slide li").mouseover(function(){
                $(me._usedimg + id + ")").fadeIn(me._speed);
                $(me._usedimg + me._lastid + ")").fadeOut(me._speed);
                me._lastid = id;
            });
        }
    }
      

  5.   

    貌似只能用变量将this储存起来