闭包定义:闭包是函数和声明该函数的词法作用域的组合。
闭包:作用域应用的特殊情况,有两种表现:函数作为参数被传递;函数作为返回值被返回。
// 函数作为返回值被返回
function create () {
const a = 100
return function () {
console.log('a--- ', a)
}
}
const fn = create ()
const a = 200
fn()
// 函数作为参数被传递
function create (fn) {
const a = 100
fn()
}
function fn() {
console.log('a --- ', a)
}
const a = 200
create(fn)