关于setInterval()里的this和细节

setInterval(fn,t);里的fn中,要使用外部类的this,则需要先将this保存起来,再使用保存的this,不能直接使用this,里面的this是指向window对象,记住setInterval()实际上是window.setInterval()就明白了。

//这是Hero类中的一个方法
Hero.prototype.shotEnemy=function(){
    switch(this.direct){
        case 0:
            var bullet=new Bullet(this.x+9,this.y,this.direct);  //创建子弹;子弹的坐标和方向与tank一致
            break;
        case 1:
            var bullet=new Bullet(this.x+30,this.y+9,this.direct);
            break;
        case 2:
            var bullet=new Bullet(this.x+9,this.y+30,this.direct);
            break;
        case 3:
            var bullet=new Bullet(this.x,this.y+9,this.direct);
            break;
    }
    this.heroBullet.push(bullet);
    heroBullet=this.heroBullet;  //需要保存下来供下面的setInterval()使用,setInterval()属于window对象,里面的this指向window,所以不能使用this.heroBullet
    heroBullet[heroBullet.length-1].t_run=setInterval("heroBullet["+(heroBullet.length-1)+"].run()",50);  //这里setInterval()里的第一个参数必须使用这种写法,下面两种写法都不行;;这里的代码实际上会生成setInterval("heroBullet[0].run()",50)这样固定下标的格式,所以会一直执行相应的对象,而下面的每次都要运算heroBullet.length-1,所以当发射多个子弹的时候,定时器总会改变为执行最后一个对象,也就会造成定时器累积导致子弹越来越快的问题

    // heroBullet[heroBullet.length-1].t_run=setInterval("heroBullet[heroBullet.length-1].run()",50);
    
    // heroBullet[heroBullet.length-1].t_run=setInterval(function(){
    //     heroBullet[heroBullet.length-1].run();
    // },50);
}
var a=[];
var i=0;
function test(){
    a.push(i++);
    setTimeout("console.log(a["+(a.length-1)+"])",100);  //输出12345
    // setTimeout("console.log(a[a.length-1])",100);  //输出5个5
}
test()
test()
test()
test()
test()
原文地址:https://www.cnblogs.com/3body/p/5417094.html