闭包的形式就是函数里面套函数,原理是保存父级函数的变量不被回收。可以在函数内部返回一个函数,把父级的变量带出去,在全局也可以访问到函数内部定义的局部变量。其实就是函数套函数,父函数的变量对于子函数来说是全局变量。当父函数执行完后,父函数内声明的变量不会被销毁,并return给全局变量b,当调用b函数的时候实际上就是调用a函数内部定义的函数,代码可以这样写:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <script> function a(){ var a1 = 0; return function(){ a1++; alert(a1); } } var b = new a(); //每调用一次 b 函数a1就会加1 等于是把父函数的变量带出来了。在全局也可以访问到局部变量。 b();b();b();b();b(); </script> </body> </html>