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

passing anonymous function as parameter in javascript

本文关键字:函数 参数 javascript      更新时间:2023-09-26

我有以下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 . animatehidelleft()函数的代码:
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);
  }
};

不幸的是,animatehidleft函数没有按预期工作。当我测试回调类型时,它警告"未定义"。

我怎样才能解决这种混乱,使我得到预期的结果?

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

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

您错过了其他地方的回调

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

那是因为你从setTimeout():

错误地调用它
EventsManager.animateHideLeft();   // No callback!

setTimeout中,您不将callback传递到下一次调用:

      EventsManager.animateHideLeft();

改为

      EventsManager.animateHideLeft(callback);

然而,测试typeof callback == "function"并不是一个坏主意,因为有时你不想/需要一个回调函数,而callback();调用会导致异常。

顺便说一句,您不应该需要clearTimeout(fr);(除非您计划在动画期间多次调用该函数)。