Javascript setInterval问题

时间:2011-06-09 05:55:31

标签: javascript

我注意到一些我无法解释的事情。我制作了这个增加或缩小蓝框的javascript代码。脚本在这里:

var animated = {

  timer : null,

  el : document.getElementById("divNavyBox"),

  startGrowAnimation : function() {

      this.stopAnimation();

      this.timer = setInterval(

          animated.doAnimation(5), 10);

  },

startShrinkAnimation : function() {

    this.stopAnimation();

    this.timer = setInterval(function() {

        animated.doAnimation(-5);

    }, 10);

},

stopAnimation : function() {

    clearInterval(this.timer);

},

doAnimation : function(amount) {

    var size = this.el.offsetWidth;



    if ((amount > 0 && size < 200) || (amount < 0 && size > 0)) {

        this.el.style.width = size + amount + "px";

        this.el.style.height = size + amount + "px";

    } else {

        this.stopAnimation();

    }

}

};

当调用动画类的startGrowAnimation方法时,框会直观地增长,直到达到某个宽度和高度。然后停止。 startGrowAnimation代码位于:

startGrowAnimation : function() {
    this.timer = setInterval(function() {
        animated.doAnimation(5);
    }, 10); 
}

此代码工作正常。但是,我不明白为什么有必要在参数中放置一个匿名函数而不仅仅是普通的调用函数。所以,我用下面的代码替换了上面的代码:

startGrowAnimation : function() {

    this.stopAnimation();

    this.timer = setInterval(animated.doAnimation(5), 10);

},

当我使用此代码时,由于某种原因,每次调用startGrowAnimation方法时,框只会增加5个像素。

那么,在这种情况下,为什么有必要在匿名函数调用中包含startGrowAnimation方法?

1 个答案:

答案 0 :(得分:4)

您尝试过的代码会调用该函数并将返回值传递给setInterval()。这显然不是你想要的。

如果您将animated.doAnimation(对函数的引用)作为回调参数,则该函数内的this值将指向window,而不是对象本身。这是因为它失去了被称为该对象方法的上下文。

因此,您必须将该方法作为对象的属性调用。这意味着您需要使用匿名函数包装器,因此它的主体可以是animated.doAnimation()

唯一的另一种方式是不值得一提,因为它调用eval()类型的函数。

相关问题