+ -
当前位置:首页 → 问答吧 → 这两种代码写法为什么会有这么大的区别?

这两种代码写法为什么会有这么大的区别?

时间:2011-10-16

来源:互联网

最近看了一段代码,感到疑惑。
有一个Player类,有start、next等方法。
请问:
1.
this.interval=setInterval(function () {_this.next();},this.timeout)与this.interval=setInterval(this.next,this.timeout)的本质区别是什么?(这句代码在第30行,我做了标记)

2.
第2句代码为什么不能正确执行,求解释!

3.
setInterval的第一个参数使用function () {}把_this.next()包含其中,是不是为了突出面向对象思想对于方法的特性?
源代码如下:
JScript code

//这是一个图片轮播器
function Player(buttons,scrollContent,imageHeight,hoverClass,timeout) {     //这里先暂且不管hoverClass
    hoverClass=hoverClass || 'hover';
    timeout=timeout || 3000;
    this.buttons=buttons;
    this.scrollContent=scrollContent;
    this.hoverClass=hoverClass;
    this.timeout=timeout;
    this.imageHeight=imageHeight;
    
    this.curItem=buttons[0];
    var _this=this;
    for (var i=0;i<this.buttons.length;i++) {
        this.buttons[i].onmouseover=function () {
            _this.stop();
            _this.invoke(this.index);
        };
        this.buttons[i].onmouseout=function () {
            _this.start();
        };
        this.buttons[i].index=i;
    }
    this.invoke(0);
}

Player.prototype={
    start:function () {
        var _this=this;
        this.stop();
        this.interval=setInterval(function () {             /*********就是这里**********/
            _this.next();
        },this.timeout);
    },
    stop:function () {
        clearInterval(this.interval);
    },
    invoke:function (n) {//具体显示哪一帧
        
        this.curItem=this.buttons[n];
        
        
        //this.scrollContent.style.top=-n*this.imageHeight+"px";
        var top=parseInt(this.scrollContent.style.top) || 0;
        this.animateIterval && this.animateIterval();
        this.animateIterval=animate(this.scrollContent,{
            top:top
        },{top:(-n*this.imageHeight)-top},1000,Tween.Quad.easeInOut);
        
        //先将所有按钮样式恢复
        this.recoverButtonsClass();
        this.curItem.className=this.hoverClass;
        
        
    },
    next:function () {
        //this.curItem.index//curItem当前的那一帧
        var nextIndex=this.curItem.index+1;
        if (nextIndex>=this.buttons.length) {
            nextIndex=0;
        }
        this.invoke(nextIndex);
    },
    recoverButtonsClass:function () {//将所有按钮样式恢复
        for (var i=0;i<this.buttons.length;i++) {
            this.buttons[i].className='';
        }
    }
};
window.onload=function () {
    var btns=getByClass('buttons')[0].getElementsByTagName('li');
    var scrollContent=getByClass('scrollContent')[0];
    var player=new Player(btns,scrollContent,150,undefined,1000);
    player.start();//开始播放
};

作者: q408384053   发布时间: 2011-10-16

this.next 内部 this-->window ...

作者: plzzz   发布时间: 2011-10-17