Last active
September 15, 2015 04:59
-
-
Save brothertao/bcb777dcc4c54259dbf2 to your computer and use it in GitHub Desktop.
闭包是什么?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function testClosure(paramClosure) { | |
var innerClosure = 100; | |
return function() { | |
paramClosure++; | |
innerClosure--; | |
} | |
} | |
var retFunc = testClosure(0); //形成(或产生)闭包,包含一个可执行的函数,还有这个函数的外部变量(不是全局变量) | |
retFunc(); //paramClosure, innerClosure 两个变量不会因为retFunc结束而消失 | |
//为什么要使用closure | |
//example:写一个counter | |
//no closure version | |
var cnt = 0; //this is a global variable, urgly and buggy!!!! | |
function counter() { | |
cnt++; | |
return cnt; | |
} | |
var c1 = counter(); //record once | |
var c2 = counter(); //record record twice | |
console.log(c1, c2); | |
//use closure version | |
function getCounter() { | |
var cnt = 0; | |
return function() { | |
cnt++; | |
return cnt; | |
} | |
} | |
var counter = getCounter(); | |
var c1 = counter(); //record once | |
var c2 = counter(); //record record twice | |
console.log(c1, c2); | |
//example (lexical scope) 词法作用域 | |
//闭包的实质就是变量作用域的问题 | |
//一个变量的作用域总是和function产生关系时候,才变得有意义 | |
//return 回来的不一定是function | |
function testScope() { | |
var cnt1 = 0; | |
var cnt2 = 0; | |
var obj = { | |
p:1 | |
}; | |
return { | |
c1: function() { | |
cnt1++; | |
return cnt1; | |
}, | |
c2: function() { | |
cnt2 = cnt2+2; | |
return cnt2; | |
}, | |
obj:obj | |
} | |
} | |
//test | |
var ret = testScope(); | |
var c1 = ret.c1(); | |
var c2 = ret.c1(); | |
var c3 = ret.c2(); | |
var c4 = ret.c2(); | |
console.log(c1, c2, c3, c4, ret); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
closure可以理解为一个只有私有变量类的一个实例