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..
Tomalak :
\n I know these are both closures\n\n\nCorrect.\n\n\n but I also think that there are some fundamental differences between the way the two are setup.\n\n\nWrong.\n\nThis:\n\nvar names = [\"zero\", \"one\", \"two\"]; // outer scope variable\nvar digit_name = function (n) { // closure -------+\n return names[n]; // outer scope variable reference |\n} // ---------------+\n\n\nand this\n\nvar digit_name = (function() { // closure --------+\n var names = [\"zero\", \"one\", \"two\"]; // outer scope variable |\n return function(n) { // closure ---+ |\n return names[n]; // outer scope variable reference | |\n } // -----------+ |\n})(); // ----------------+\n\n\nis exactly the same thing, functionally, the only real difference being the number of closures.\n\nEvery function in JavaScript creates a closure, it's as simple as that.\n\nDon'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.",
2016-01-05T17:16:06