问题描述
var names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight"];
var digit_name = function(n){
return names[n];
}
//Execute
digit_name(0)
VERSUS
var digit_name = (function() {
var names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight"];
return function(n) {
return names[n];
}
})();
然后像这样执行它:
digit_name(2)
我知道这两个都是闭包,但是我也认为两者的设置方式之间存在一些根本性的区别.有人可以指出这两种设置有何不同(特别是考虑到两者都完成相同的工作)吗?我可以想到将一个全局变量附加到窗口"与嵌套函数以模拟私有变量.
I know these are both closures, but I also think that there are some fundamental differences between the way the two are setup. Can someone point out how different are these two setups (especially considering both get the same job done)? Attaching a global variable to the 'window' vs nesting functions to emulate private variable is one I can think of..
编辑-我现在很困惑是否将第一个设置视为一个闭包...使用chrome,我研究了这两个设置.
EDIT - I am now confused whether to think of the first setup as a closure or not...Using chrome, I investigated the two setups..
var digit_name = (function() {
var names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight"];
return function(n) {
return names[n];
}
})();
undefined
console.dir(digit_name)
function anonymous(n)
arguments: null
caller: null
length: 1
name: ""prototype: Object
__proto__: function()
<function scope>
Closure names: Array[9]
With Block: CommandLineAPI
Global: Window
但是对于chrome中的第一个功能,
However for the first function in chrome,
var names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight"];
var digit_name = function(n){
return names[n];
}
undefined
console.dir(digit_name)
function digit_name(n)
arguments: null
caller: null
length: 1
name: ""
prototype: digit_name
__proto__: function()
<function scope>
With Block: CommandLineAPI
Global: Window
您可以看到Chrome明确指示第一个设置存在闭包,而第二个设置则不存在.
You can see that Chrome explicitly indicates the existence of closure for the first setup, but not for the second setup..
推荐答案
正确.
错.
此:
var names = ["zero", "one", "two"]; // outer scope variable
var digit_name = function (n) { // closure -------+
return names[n]; // outer scope variable reference |
} // ---------------+
还有这个
var digit_name = (function() { // closure --------+
var names = ["zero", "one", "two"]; // outer scope variable |
return function(n) { // closure ---+ |
return names[n]; // outer scope variable reference | |
} // -----------+ |
})(); // ----------------+
在功能上,
是完全相同的东西,唯一真正的区别是闭包的数量.
is exactly the same thing, functionally, the only real difference being the number of closures.
JavaScript中的每个function
都会创建一个闭合,就这么简单.
Every function
in JavaScript creates a closure, it's as simple as that.
不要让设置闭包的不同方式(函数语句,函数表达式或立即执行的函数表达式)使您感到困惑,最终它们全都是同一件事.
Don't let the different ways of setting up closures (function statements, function expressions or immediately-executed function expressions) confuse you, ultimately it all amounts to the same thing.
这篇关于简单闭包与带有嵌套函数返回的闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!