Closures
the first example code:
function outer() {
let a = 10
function fn() {
console.log(a)
}
// console.log(fn) // fn is a function
return fn
}
// console.log(outer())
// outer() is exactly equal to the function fn
// outer() == fn == function fn(){...}
const fun = outer()
fun() // the console prints 10
// console.log(fun()) // the console prints 'undefined', because the function fn doesn't return a significant value
remember that const fun=outer()
not const fun=outer
, in other words, fun is the return value of the function outer
in the second example, the inner anonymous function is used as the return value of the function outer:
function outer(){
let a=10
return function(){
console.log(a)
}
}
// outer() is equal to the anonymous function
const fun=outer()
fun() // call the anonymous function, the console prints 10