有具体名称的匿名函数var bar = function foo(){}
2024-09-14 12:36:39
http://kangax.github.io/nfe/
命名的函数表达式
函数表达式实际上可以经常看到。Web开发中的一个常见模式是基于某种特性测试来“分叉”函数定义,从而获得最佳性能。由于这种分叉通常发生在相同的范围内,所以几乎总是需要使用函数表达式。毕竟,就我们现在所知,函数声明不应该有条件地执行:
// `contains` is part of "APE Javascript library" (http://dhtmlkitchen.com/ape/) by Garrett Smith
var contains = (function() {
var docEl = document.documentElement;
if (typeof docEl.compareDocumentPosition != 'undefined') {
return function(el, b) {
return (el.compareDocumentPosition(b) & 16) !== 0;
};
}
else if (typeof docEl.contains != 'undefined') {
return function(el, b) {
return el !== b && el.contains(b);
};
}
return function(el, b) {
if (el === b) return false;
while (el != b && (b = b.parentNode) != null);
return el === b;
};
})();
很明显,当一个函数表达式有一个名称(技术上的标识符)时,它被称为命名函数表达式。你在第一个例子中看到的var bar = function foo(){};
- 就是那个 - 一个名为函数的函数表达式foo
。需要记住的一个重要细节是,这个名称只在新定义的函数的范围内可用 ; 规范要求标识符不应该被封闭的范围使用:
var f = function foo(){
return typeof foo; // "foo" is available in this inner scope
};
// `foo` is never visible "outside"
typeof foo; // "undefined"
f(); // "function"
那么这些命名的函数表达式有什么特别之处呢?我们为什么要给他们的名字呢?
看来,命名的功能使得调试体验更加愉快。调试应用程序时,调用堆栈和描述性项目会产生巨大的差异。
最新文章
- POI导出excel日期格式
- jffs2和yaffs2文件系统制作工具的编译与使用
- Codeforces Round #346 (Div. 2)E - New Reform(DFS + 好题)
- 常用终端及git命令
- sql - and - or
- 初谈SQL Server逻辑读、物理读、预读【转】
- cf479A Expression
- Caused by: java.lang.RuntimeException: by java.lang.OutOfMemoryError: PermGen space(tomcat 启动时提示内存溢出)
- EECS 649 Introduction to Artificial Intelligence
- npm安装cnpm、vue、react
- 美化你的GRUB,全面支持中文(菜单、提示、帮助)适用7.04-9.04
- OpenStack的架构详解[精51cto]
- MySQL Crash Course #19# Chapter 27. Globalization and Localization
- [转贴] start-stop-daemon命令
- 170620、springboot编程之页面版Hello World
- ConcurrentHashMap实现解析
- PlSQL Oracle 中的 对应 SQL server 中的 IsNull(Expr1,Expr2)
- 物料类型AM11没有任务清单类型N定义
- UVA-10765 Doves and bombs (双连通分量)
- 慎用WSACleanup()
热门文章
- D02 TED Elon Mulsk The future we're building — and boring
- 用maven建立java web项目
- atom添加eslint插件
- JavaScript循环实例
- Microsoft Visual Studio 2012旗舰版(VS2012中文版下载)官方中文版
- ExperDot的博客目录导航
- centos 7 部署 open-falcon 0.2.0
- flask 分页
- 【转】nginx提示:500 Internal Server Error错误的解决方法
- 怎么为WebStorm更换主题 修改字体样式