javascript tutorial - [Solved-5 Solutions] How do javascript closures work - javascript - java script - javascript array
Problem:
Explain JavaScript Closure ?
Solution 1:
Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!
This article is intended for programmers with some programming experience in a mainstream language, and who can read the following JavaScript function:
function sayHello(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
say();
}
sayHello('Joe');
click below button to copy the code. By JavaScript tutorial team
Solution 2:
This example shows that the local variables are not copied they are kept by reference
function say667() {
// Local variable that ends up within closure
var num = 42;
var say = function() { console.log(num); }
num++;
return say;
}
var sayNumber = say667();
sayNumber(); // logs 43
click below button to copy the code. By JavaScript tutorial team
Solution 3:
All three global functions have a common reference to the same closure because they are all declared within a single call to setupSomeGlobals()
.
var gLogNumber, gIncreaseNumber, gSetNumber;
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 42;
// Store some references to functions as global variables
gLogNumber = function() { console.log(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
setupSomeGlobals();
gIncreaseNumber();
gLogNumber(); // 43
gSetNumber(5);
gLogNumber(); // 5
var oldLog = gLogNumber;
setupSomeGlobals();
gLogNumber(); // 42
oldLog() // 5
click below button to copy the code. By JavaScript tutorial team
Solution 4:
This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + i;
result.push( function() {console.log(item + ' ' + list[i])} );
}
return result;
}
function testList() {
var fnlist = buildList([1,2,3]);
// Using j only to help prevent confusion -- could use i.
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
testList() //logs "item2 undefined" 3 times
click below button to copy the code. By JavaScript tutorial team
Solution 5:
This example shows that the closure contains any local variables that were declared inside the outer function before it exited. Note that the variable alice
is actually declared after the anonymous function. The anonymous function is declared first; and when that function is called it can access the alice
variable because alice
is in the same scope (JavaScript does variable hoisting). Also sayAlice()()
just directly calls the function reference returned from sayAlice()
— it is exactly the same as what was done previously but without the temporary variable.
function sayAlice() {
var say = function() { console.log(alice); }
// Local variable that ends up within closure
var alice = 'Hello Alice';
return say;
}
sayAlice()();// logs "Hello Alice"