What are the benefits to using anonymous functions instead of named functions for callbacks and parameters in JavaScript event code?
I use anonymous functions for three reasons:
- If no name is needed because the function is only ever called in one place, then why add a name to whatever namespace you're in.
- Anonymous functions are declared inline and inline functions have advantages in that they can access variables in the parent scopes. Yes, you can put a name on an anonymous function, but that's usually pointless if it's declared inline. So inline has a significant advantage and if you're doing inline, there's little reason to put a name on it.
- The code seems more self-contained and readable when handlers are defined right inside the code that's calling them. You can read the code in almost sequential fashion rather than having to go find the function with that name.
I do try to avoid deep nesting of anonymous functions because that can be hairy to understand and read. Usually when that happens, there's a better way to structure the code (sometimes with a loop, sometimes with a data table, etc...) and named functions isn't usually the solution there either.
I guess I'd add that if a callback starts to get more than about 15-20 lines long and it doesn't need direct access to variables in the parent scope, I would be tempted to give it a name and break it out into it's own named function declared elsewhere. There is definitely a readability point here where a non-trivial function that gets long is just more maintainable if it's put in its own named unit. But, most callbacks I end up with are not that long and I find it more readable to keep them inline.
最新文章
- CacheManager:–个通用缓存接口抽象类库
- Android studio每次启动卡在fetching Android sdk compoment information的解决方案
- Autofac 同时支持MVC 与Webapi
- Eclipse中的Link with Editor功能是如何实现
- stl学习(一)优先队列
- [asp.net core]project.json(2)
- ubuntu自动关闭屏幕显示器
- Apache开启不了------The requested operation has failed!
- Apple 预计于内华达州雷诺市再盖一个数据中心
- 计算时间间隔的js
- 1061: [Noi2008]志愿者招募 - BZOJ
- java文件处理工具类
- Xmanager4使用记录
- [Echarts]用Echarts绘制饼状图
- LDMIA、LDMIB、LDMDB、LDMDA、STMIA、LDMFD、LDMFA、LDMED、LDMEA指令详解
- python小整数与str数据池,编码关系
- left join,right join,inner join
- 20170922xlVBA_GetCellTextFromWordDocument
- Spring boot 启动配置原理
- weblogic控制台部署web应用