时间:2021-07-01 10:21:17 帮助过:57人阅读
var counter = function() {
var counter = 0
return function() {
return counter++
}
}
var anotherCounter = counter()
console.log(anotherCounter())
console.log(anotherCounter())
console.log(anotherCounter())
片面地讲 闭包就是 “北京城”,一层一层的控制,皇宫的皇上看上城内的妹子就可以用,城内的汉子要么用城内的妹子,要么去城外 =。=
把数据和作用域绑定到一起就是闭包。
可以学习下做下面几道题:Learning Advanced JavaScript
通过引用变量从而阻止该变量被垃圾回收的机制
将一个上下文的私有变量的生命周期延长的机制
搬运一下 @winter 的blog 闭包概念考证 · Issue #3 · wintercn/blog · GitHub
// One of JavaScript's most powerful features is closures. If a function is
// defined inside another function, the inner function has access to all the
// outer function's variables, even after the outer function exits.
function sayHelloInFiveSeconds(name){
var prompt = "Hello, " + name + "!";
// Inner functions are put in the local scope by default, as if they were
// declared with `var`.
function inner(){
alert(prompt);
}
setTimeout(inner, 5000);
// setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
// exit immediately, and setTimeout will call inner afterwards. However,
// because inner is "closed over" sayHelloInFiveSeconds, inner still has
// access to the `prompt` variable when it is finally called.
}
sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s
var globalVal=null;
var fn=function(){
var a=1;
globalVal=function(){
a++;
console.log(a);
}
}
fn();
globalVal();//2
globalVal();//3