var names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight"];
var digit_name = function(n){
return names[n];
}
//Execute
digit_name(0)
对比
var digit_name = (function() {
var names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight"];
return function(n) {
return names[n];
}
})();
然后像这样执行:
digit_name(2)
我知道这都是闭包,但我也认为两者的设置方式存在一些根本区别。有人可以指出这两种设置有多么不同(特别是考虑到两者都完成相同的工作)?我能想到的一个方案是,将全局变量附加到“窗口”与嵌套函数来模拟私有(private)变量。
编辑 - 我现在很困惑是否将第一个设置视为关闭...使用 chrome,我研究了这两个设置..
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 中的第一个函数,
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 明确指示第一个设置存在闭包,但第二个设置则不存在闭包。
最佳答案
I know these are both closures
正确。
but I also think that there are some fundamental differences between the way the two are 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 | |
} // -----------+ |
})(); // ----------------+
在功能上是完全相同的,唯一真正的区别是闭包的数量。
JavaScript 中的每个函数
都会创建一个闭包,就这么简单。
不要让设置闭包的不同方式(函数语句、函数表达式或立即执行的函数表达式)让您感到困惑,最终它们都等同于同一件事。
关于javascript - 简单闭包与带有嵌套函数返回的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34615754/