Last active
September 13, 2016 10:09
-
-
Save cyb3rD/c3209af94196320aa569e1458cf411c1 to your computer and use it in GitHub Desktop.
Sample closure understanding code
This file contains hidden or 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
| //Closure example | |
| function greet(whatToSay) { | |
| // get value back when invoke function | |
| // get back function | |
| return function(name) { | |
| console.log(whatToSay + ' ' + name); | |
| }; | |
| } | |
| var sayHi = greet('Hi'); | |
| sayHi('Nikolay'); | |
| // example of closures | |
| function buildFunctions() { | |
| var arr = []; | |
| for (var i = 0; i < 3; i++) { | |
| arr.push( | |
| // !!! _creating_new_function_object_ and putting to the array | |
| // Has access to i var | |
| function() { | |
| console.log(i); | |
| } | |
| ); | |
| } | |
| return arr; // array with three functions | |
| } | |
| console.log('==================='); | |
| var fs = buildFunctions(); | |
| // invoking functions | |
| fs[0](); // 3 | |
| fs[1](); // 3 | |
| fs[2](); // 3 | |
| function letBuildFunctions() { | |
| var arr = []; | |
| for (var i = 0; i < 3; i++) { | |
| // block Scope | |
| let j = i; | |
| arr.push( | |
| function() { | |
| console.log(j); | |
| } | |
| ); | |
| } | |
| return arr; // array with three functions | |
| } | |
| console.log('==================='); | |
| var fsLet = letBuildFunctions(); | |
| // invoking functions | |
| fsLet[0](); | |
| fsLet[1](); | |
| fsLet[2](); | |
| // Separate execution contex | |
| function scopeBuildFunctions() { | |
| var arr = []; | |
| for (var i = 0; i < 3; i++) { | |
| arr.push( | |
| //IIFE - _execute_ function | |
| (function(j) { | |
| // Has accees to the vars in execution context of the ext function | |
| return function() { | |
| console.log(j); | |
| } | |
| }(i)) // pass var i | |
| ); | |
| } | |
| return arr; // array with three functions | |
| } | |
| console.log('==================='); | |
| var fsScope = scopeBuildFunctions(); | |
| // invoking functions | |
| fsScope[0](); | |
| fsScope[1](); | |
| fsScope[2](); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment