在javascript中传递匿名函数作为参数
passing anonymous function as parameter in javascript
我有以下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);
(除非您计划在动画期间多次调用该函数)。
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 为什么不'我们在javascript中使用函数参数的数据类型
- 使用闭包共享构造函数参数
- 函数参数的值错误
- 当一个重要的构造函数参数丢失时应该发生什么
- 阻止ReSharper将JavaScript函数参数放到新行中
- 根据函数参数将CSS值存储在var中,然后对其进行操作
- 使构造函数参数具有ES6类方法的特权
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- Windows.Networking.EndpointPair构造函数参数
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 大括号中的Javascript函数参数
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 将JSON字符串转换为函数参数
- eval()读取函数参数有多糟糕
- Javascript不能在一个命令中使用函数参数
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- ES6类构造函数参数
- 是否可以在javascript函数参数列表中调用多个函数