+ 2

Need help with understanding 'Closure' in JS

As per my understanding, "A Function creates a closure over a variables, So when the function is called the value of variable is used as what it was initially instead of replacing with a new value, if it's changed meanwhile. " Is my understanding of Closure correct? May I request any SoloLearn member to explain the closure briefly with an example? Thanks,

9th Dec 2016, 2:22 PM
Mohammed Haseeb
Mohammed Haseeb - avatar
2 Respuestas
+ 2
In practical live are closures used for hiding same parts of implementation like in OOP using local variables and functions. In JavaScript are all objects/variables visible in the scope so we can use closures to make private "properties" or "methods". Look at this: var counter = (function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function() { changeBy(1); }, decrement: function() { changeBy(-1); }, value: function() { return privateCounter; } }; })(); var v1 = counter.value(); // = 0 counter.increment(); counter.increment(); var v2 = counter.value(); // = 2 counter.decrement(); var v2 = counter.value(); // = 3 This example is taken from MDN where are closures explained: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures Other example could be my Simple Calendar Widget - you can find it in my Playground.
9th Dec 2016, 3:12 PM
Ondřej Doněk
Ondřej Doněk - avatar
0
Thanks a lot for the example and explaination. :-)
9th Dec 2016, 4:10 PM
Mohammed Haseeb
Mohammed Haseeb - avatar