This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myFunctions= []; | |
function createMyFunction(i) { | |
return function() { | |
console.log("My value: " + i); | |
}; | |
} | |
for (var i = 0; i < 3; i++) { | |
myFunctions[i] = createMyFunction(i); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myFunctions = []; | |
for (var i = 0; i < 3; i++) { // let's create 3 functions | |
myFunctions[i] = function() { // and store them in myFunctions | |
console.log("My value: " + i); // each should log its value. | |
}; | |
} | |
for (var j = 0; j < 3; j++) { | |
myFunctions[j](); // and now let's run each one to see | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function outerFunction(x) { | |
var z = 3; | |
return function (y) { | |
x=x+1;//x++ | |
alert(x + y + z); | |
} | |
} | |
var myVal = 2; | |
var innerFunction = outerFunction(myVal); // innerFunction is now a closures. | |
innerFunction(10); //will alert 16 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function outerFunction(x) { | |
var z = 3; | |
return function (y) { | |
alert(x + y + z); | |
} | |
} | |
var innerFunction = outerFunction(2); // innerFunction is now a closures. | |
innerFunction(10); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sayHelloToClosures(yourName) { | |
var text = 'Hello Closures from' + yourName; | |
var sayAlert = function() { alert(text); } | |
} |