匿名函数的应用场景
- 箭头函数(无法设置名字)
const fn = () => {};
- 函数表达式
const fn = function () {};
document.onclick = function () {};
function fn() {
return function () {};
}
- 回调函数
setTimeout(function () {}, 1000);
fn(function () {});
- 自执行函数
(function(){
})();
匿名函数具名化
- 具名化的的名字可以在函数内部上下文中使用,代表当前函数本身
var fn = function sum() {
console.log(sum); //[Function: sum]
};
console.log(sum); //Uncaught ReferenceError: sum is not defined
//匿名函数具名化后的这个名字,在所处上下文中未被声明过
fn();
- 具名化的名字在函数内部是不允许被修改值的
(function sum() {
sum = 1;
console.log(sum); //[Function: sum]
})();
- 具名化的名字权重比较低,但凡当前私有上下文中存在一个同名的私有变量,都以私有变量为主,不再是这个函数
(function sum() {
console.log(sum); //=>Uncaught ReferenceError: Cannot access 'sum' before initialization
let sum = 1;
console.log(sum); //=>1
})();
匿名函数具名化的作用
方便匿名函数递归处理,而且更符合规范
"use strict";
let i = 0;
(function sum() {
i++;
console.log(i);
if (i < 2) {
sum();
}
})();
"use strict";
(function () {
console.log(arguments.callee); //获取的是当前函数本身,
//但是在JS严格模式下,不允许使用callee
//「Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them」
})();