+ 3
I understand how global scopes work but Im having a hard time understanding closures
I know how the scopes of variables work...like the inner most function is able to use all the outer functions variables and the outer most function can only access its own variable/s.What im dtrughling with is how this actually works ,as in how you can use it in a program.
2 odpowiedzi
+ 3
Regarding closure, here is David Carroll's pick of 3 readings from beginner to advanced:
https://www.sololearn.com/post/45261/?ref=app
The third link should answer your first question of how closure works.
For your second question, closure can be used for
1. Creating static variable.
Check the Example by Calvin:
https://www.sololearn.com/post/45035/?ref=app
2. For some design patterns:
Reading :
https://blog.bitsrc.io/understanding-design-patterns-in-javascript-13345223f2dd
+ 4
Here some examples:
Encapsulation:
First example, without closure, internal data is accessed
https://code.sololearn.com/W3Ll516TP4nJ/?ref=app
Second example encapsulating with closure
https://code.sololearn.com/WOpNHxd83Nrw/?ref=app
This is an example of using module design pattern
https://code.sololearn.com/WAorgga5LZs4/?ref=app