Minimum viable JavaScript closure
The top answer on Stack Overflow regarding JavaScript closures defines them as (paraphrase):
A function that simply accesses variables outside of your immediate lexical scope that are not deallocated after the function returns.
Based strictly on this definition it seems like we can reduce the minimum viable closure (that does something useful) to a function containing no local variables that alters something in the global scope:
var x = 0;
function foo() {
x = x + 1;
return x;
}
foo(); // returns 1
foo(); // returns 2, et cetera
However, usual examples contain nested functions and variables that are "enclosed". Is this example a closure (or perhaps the global scope is now the closure)? Or is the definition incomplete?
Thanks!
Yes, it is a closure. In the top answer, it actually provides a simplest closure example:
var a = 10;
function test() {
console.log(a); // will output 10
console.log(b); // will output 6
}
var b = 6;
test();
This is basically identical to your example, the scope of the function definition just happens to be the same as the parent of execution context.
When a Javascript function is invoked, a new execution context is created. Together with the function arguments and the parent object, this execution context also receives all the variables declared outside of it (in the above example, both 'a' and 'b').
You can actually use a new scope to replace the global scope in your example:
(function(){
var x = 0;
function foo(){
x = x + 1;
console.log(x);
}
foo(); // output 1
foo(); // output 2
})();
No, because you simply don't use a closure here, there's only one scope, the global one, you're just using a global variable.
The definition you cite is ambiguous there :
after the function returns
In this definition, the "function" which "returns" is the one whose scope holds the variable, that is the external one. As there's no outer function, and the global scope never ends, there's no closure.
A closure would be like this :
var foo = (function(){
var x = 0;
return function() {
x = x + 1;
return x;
}
})(); // the function returns but x keeps being usable by the inner function
foo(); // returns 1
foo(); // returns 2, et cetera
And a less useless closure would be like this :
function makeFoo(){
var x = 0;
return function() {
x = x + 1;
return x;
}
}
var foo1 = makeFoo(), foo2 = makeFoo();
foo1(); // returns 1
foo2(); // returns 1
foo1(); // returns 2, et cetera
链接地址: http://www.djcxy.com/p/51612.html
上一篇: JavaScript动态关闭范围
下一篇: 最小可行的JavaScript关闭