闭包是函数内的函数,返回的是函数,类似于父子函数,子函数就是闭包。
函数的外部能读取到函数内部的值,就形成了闭包。
优点:让局部变量不回收,可以在外部更改函数内部的值,再次调用时产生不同结果。
缺点:用多了很占用内存。
例子:改变了函数的返回值
var f1=function(){ var a=1 var f2=function(x=a){ a=x console.log("a",a) } return f2 } var a1=f1() a1()//1 a1(2) a1()//2