Skip to content
快速预览

匿名函数

✍️ chunyi.wang 🕒 2023-07-18 07:49:25(10 months ago) 🔗 A.前端知识整理

如果在传入一个函数时,我们没有指定这个函数的名词或者通过函数表达式指定函数对应的变量,那么这个函数称之为匿名

  1. 箭头函数是匿名函数「无法设置名字,变量接收可以理解为是它的名字」
js
const fn = () => {};
  1. 函数表达式一般是匿名函数
js
const fn = function () {};
document.onclick = function () {};
function fn() {
    return function () {};
}
  1. 回调函数一般也是匿名函数
js
setTimeout(function () {}, 1000);
fn(function () {});
  1. 自执行函数一般也是匿名函数
js
(function(){

})();

(function(fn) {
console.log("立即执行函数被调用")
}());

使用技巧

js
var fn = function sum() {
    console.log(sum); //具名化的名字可以在函数内部上下文中使用,代表当前函数本身
};
// console.log(sum); //Uncaught ReferenceError: sum is not defined  匿名函数具名化后的这个名字,在所处上下文中未被声明过
fn();
js
(function sum() {
    sum = 1;
    console.log(sum); //=>打印还是函数  具名化的名字在函数内部是不允许被修改值的
})();
js
(function sum() {
    // 具名化的名字权重比较低,但凡当前私有上下文中存在一个同名的私有变量,都以私有变量为主,不再是这个函数
    console.log(sum); //=>Uncaught ReferenceError: Cannot access 'sum' before initialization
    let sum = 1;
    console.log(sum); //=>1
})();
js
// 作用:方便匿名函数递归处理,而且更符合规范
 "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」
})(); 

 "use strict";
let i = 0;
(function sum() {
    i++;
    console.log(i);
    if (i < 2) {
        sum();
    }
})();

Released under the MIT License.