You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Closures in JavaScript can be a difficult concept to grasp for those either new to the language or new to programming. As part of my own learning process I want to explain closures here to anyone who has struggled to find a simple and concise set of examples.
3
+
4
+
## What problem do closures solve?
5
+
Closures are one way to solve the problem of having private variables in Javascript.
6
+
7
+
In a language like C#, the "private" keyword can be used to protect class members from being directly accessed from outside the class.
8
+
9
+
Example below taken from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private
10
+
```c#
11
+
classEmployee
12
+
{
13
+
privatestringname="FirstName, LastName";
14
+
privatedoublesalary=100.0;
15
+
16
+
publicstringGetName()
17
+
{
18
+
returnname;
19
+
}
20
+
21
+
publicdoubleGetSalary()
22
+
{
23
+
returnsalary;
24
+
}
25
+
}
26
+
27
+
classPrivateTest
28
+
{
29
+
staticvoidMain()
30
+
{
31
+
Employeee=newEmployee();
32
+
33
+
// The data members are inaccessible (private), so
0 commit comments