2021-06-13 JS中的匿名函数

匿名函数的应用场景

  1. 箭头函数(无法设置名字)
const fn = () => {};
  1. 函数表达式
const fn = function () {};
document.onclick = function () {};
function fn() {
    return function () {};
}
  1. 回调函数
setTimeout(function () {}, 1000);
fn(function () {});
  1. 自执行函数
(function(){

})();

匿名函数具名化

  1. 具名化的的名字可以在函数内部上下文中使用,代表当前函数本身
var fn = function sum() {
    console.log(sum); 	//[Function: sum]
};
console.log(sum); //Uncaught ReferenceError: sum is not defined
 				 //匿名函数具名化后的这个名字,在所处上下文中未被声明过
fn();
  1. 具名化的名字在函数内部是不允许被修改值的
(function sum() {
    sum = 1;
    console.log(sum); //[Function: sum]
})();
  1. 具名化的名字权重比较低,但凡当前私有上下文中存在一个同名的私有变量,都以私有变量为主,不再是这个函数
(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」
})();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值