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];
}
})();
then execute it like this:
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..
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
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
You can see that Chrome explicitly indicates the existence of closure for the first setup, but not for the second setup..