-
-
Save mdrmtz/d0085d7934cca5cb3651 to your computer and use it in GitHub Desktop.
Closure
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
| //IIEF don't populate window namespace | |
| (function () { | |
| // Create a name space | |
| var answers = answers || {}; | |
| answers = { | |
| meta: function (fn) { | |
| console.log("en meta"); | |
| fn(); | |
| }, | |
| fun: function () { | |
| console.log("funcion"); | |
| }, | |
| makeClosure: function (fn) { | |
| var _this = this; | |
| return function () { | |
| return fn(_this.fun); | |
| }; | |
| }, | |
| testIIFE: function (lista) { | |
| var _this = this; | |
| for (var i = 0; i < lista.length; i++) { | |
| (function () { | |
| return lista[i](_this.fun); | |
| }()); | |
| } | |
| }, | |
| testClosure: function (lista) { | |
| for (var i = 0; i < lista.length; i++) { | |
| this.makeClosure(lista[i])(); | |
| } | |
| } | |
| }; | |
| var lista = [answers.meta, answers.meta, answers.meta]; | |
| answers.testIIFE(lista); | |
| answers.testClosure(lista); | |
| }()); |
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
| (function () { | |
| function meta(f) { | |
| console.log("en meta"); | |
| //Invoke f | |
| f(); | |
| } | |
| var lista = [meta, meta, meta]; | |
| var fun = function () { | |
| console.log("funcion"); | |
| } | |
| var makeClosure = function (fn) { | |
| return function () { | |
| return fn(fun); | |
| }; | |
| }; | |
| //Using function create scope | |
| for (var i = 0; i < lista.length; i++) { | |
| makeClosure(lista[i])(); | |
| } | |
| //Using an IIFE | |
| for (var i = 0; i < lista.length; i++) { | |
| (function () { | |
| return lista[i](fun); | |
| }()) | |
| } | |
| fun(); | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment