gpt4 book ai didi

Javascript setInterval 问题

转载 作者:行者123 更新时间:2023-11-29 18:32:44 27 4
gpt4 key购买 nike

我注意到一些我无法解释的事情。我制作了这个增大或缩小蓝色框的 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 方法时,框的大小只会增加五个像素。

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

最佳答案

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

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

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

唯一不值得一提的其他方法是调用 eval() 类型的函数。

关于Javascript setInterval 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com