js closure
scope:
in js, inner function has access to params/local variable of the outer function,
closure:
variable use the scope where they are defined, even apparently the scope is finished,
inner function:
a inner function will always has access to the scope which defined it - the outer function, even after the outer function already finished execution,
when to use closure:
usually used with inner function, for:
* access local variable even after it outer function execution finished,
* make variable private, only could be accessed by the inner function,
------
e.g.
example 1:
var scope = "global scope";
function checkscope() {
var scope = "local scope";
function f() { return scope; }
return f;
}
checkscope()(); // => "local scope"
example 2:
var uniqueInteger = (function() {
var counter = 0;
return function() { return counter++; }; // the returned function is the only one who can access the counter variable,
}());
for(var i=1;i<5;i++) {
console.log(uniqueInteger());
}
example 3:
function counter() {
var n = 0;
return { // the returned object, is the only one who has access to the variable n,
count: function() { return n++; },
reset: function() { n = 0; }
};
}
var n1 = counter();
var n2 = counter();
console.log(n1.count());
console.log(n2.count());
console.log(n1.count());
console.log(n2.count()); // n1 & n2 has separate scope, they has different n, and don't effect each other,
n1.reset();
console.log(n1.count());
console.log(n2.count());
------
668

被折叠的 条评论
为什么被折叠?



