转载请注明出处
原文连接 http://blog.cheerspublishing.cn/article/5b698f05b8ea642ea9213f4f
闭包在JavaScript 中是一个非常重要的概念。
闭包例子
function outer() {
var loc = 30; return loc;};console.log(outer()); //30
outer
函数是一个函数声明,有一个局部变量loc
赋值为30,返回loc
。
当这个函数调用之后,局部变量就会被释放了,
function outer() {
var loc = 30; return function() {
return loc; };};var func = outer();console.log(func()); //30
这个outer
函数有一个loc
的局部变量,返回值是一个匿名函数表达式,在这个函数表达式又返回outer
函数的loc
局部变量,这种情况loc
是不会被释放掉的。
调用var func = outer();
返回的是一个匿名函数,这个匿名函数里面仍然能够访问到outer()
de 局部变量loc
,当outer()
函数被调用之后,func()
这个函数再次调用的时候仍然能访问到它外层outer()
函数的局部变量loc
。 这种情况就是我们通常所说的闭包。
那么闭包的作用是什么呢?在前端编程里,闭包是非常常见的
闭包无处不在
<body><input type="button" value="按钮" id="but"><script type="text/javascript">var but = document.getElementById("but");! function() {
var loc = 0; but.onclick = function() {
console.log(loc++); };}();script>body>