5

我不知道如何问现在在我脑海里嗡嗡作响的问题,所以请耐心等待。我是异步编程的新手,我认为最好的学习方法是制作一个小的 javascript pong 游戏。我从一个 shootball() 函数开始,然后在另一个 div 周围反弹一个 div。我如何做到这一点是这样的:

function shootball(angle, speed){
    angle = (angle/360.0)*2*Math.PI;
    var ballmotion = setInterval(function(){
        var nowx, nowy, minusY, plusX;
        nowx = $("#ball").position().left;
        nowy = $("#ball").position().top;
        minusY = Math.sin(angle) * 4.0;
        plusX = Math.cos(angle) * 4.0;
        if(hitsWall(nowx+plusX, nowy-minusY)){
            clearInterval(ballMotion);
            shootball(newAngle(nowx+plusX, nowy-minusY), speed);
        }
        $("#ball").css("left", (nowx + plusX)).css("top", (nowy - minusY));
     }, 10/speed);
}

我不是大的不必要递归的忠实粉丝,但我只是想尝试一下。瞧,它完全按照我的预期工作。但是当我开始充实程序的其余部分时,我突然想到我无法避免这种递归性质。所以我的问题是:javascript 是否以某种方式识别调用 clearInterval 后调用“shootball”函数基本上完成了?或者这真的会发现自己在我的堆栈中加载了不必要的激活记录?提前感谢您提供的任何专业知识。

4

1 回答 1

4

Does javascript somehow recognize that the calling "shootball" function is essentially finished after calling clearInterval?

No, shootball was finished long ago, right after the assignment to ballmotion. However, its variable scope (angle, speed, ballmotion and the parent scope) did persist since the anonymous function built a closure with it and was referenced from outside (from the scheduler). And that scope will get garbage collected after the clearInterval call which removed the references to it.

does this really find itself loading up my stack with unnecessary activation records?

No. Every function that is executed via setTimeout/setInterval runs in its own execution context, with a brand new call stack.

于 2013-06-13T15:04:17.450 回答