gpt4 book ai didi

javascript - 在javascript中将匿名函数作为参数传递

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:38 24 4
gpt4 key购买 nike

我有以下 javascript 代码:

   EventsManager.prototype.hideContainer = function()
{
var that = this;

var index = that.getNextUnreadEventIndex();
if(index !== -1)
{
EventsManager.animateHideLeft(function() //<--- passing a function as parameter to another function
{
var unreadEvent = that.eventsList.splice(index,1)[0];
unreadEvent.isEventOnFocus = true;

that.eventsList.push(unreadEvent);
that.displayLastEvent();
});
}
}

这是 EventsManager.animateHideLeft() 函数的代码:

EventsManager.animateHideLeft = function(callback)
{
var p = document.getElementById("eventsContainer");
var width = parseFloat(p.style.width);

if(!width || width === "NaN") width = 200;

if(width <= 10)
{
clearTimeout(fr);
alert(typeof callback); //<-- this shows "undefined"
callback();
}
else
{
width = width - 10;

p.style.width = width + "px";

fr = setTimeout(function()
{
EventsManager.animateHideLeft();
}, 50);
}
};

不幸的是,函数 animateHideLeft 没有按预期工作。当我测试 typeof 回调时,它会提示“未定义”。

我怎样才能解决这种困惑,以便获得预期的结果?

最佳答案

看起来您只需要通过 setTimeout 中的调用传递 callback

fr = setTimeout(function()
{
EventsManager.animateHideLeft(callback);
}, 50);

关于javascript - 在javascript中将匿名函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15533822/

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