闭包的概念
概念
内层函数可以访问到外层函数的变量和参数,即一个函数和它周围状态捆绑在一起的组合。
举例
-
函数作为返回值
// 函数作为返回值
function test(){const a = 1;return function() {console.log('a:',a);}
}const fn = test();
const a = 6;
fn(); // 1
2. 函数作为参数
// 函数作为参数
function test(fn){const b = 2;fn();
}const b = 8;
function fn(){console.log('b',b);
}
test(fn); // 8
参考
彻底掌握JS闭包,只要2分钟!_哔哩哔哩_bilibili