Skip to content

Commit 32a4d3e

Browse files
authored
Update README.md
1 parent ca67b11 commit 32a4d3e

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

README.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,46 @@
1-
# JavaScript-Closures
1+
# JavaScript-Closures
2+
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+
class Employee
12+
{
13+
private string name = "FirstName, LastName";
14+
private double salary = 100.0;
15+
16+
public string GetName()
17+
{
18+
return name;
19+
}
20+
21+
public double GetSalary()
22+
{
23+
return salary;
24+
}
25+
}
26+
27+
class PrivateTest
28+
{
29+
static void Main()
30+
{
31+
Employee e = new Employee();
32+
33+
// The data members are inaccessible (private), so
34+
// they can't be accessed like this:
35+
// string n = e.name;
36+
// double s = e.salary;
37+
38+
// 'name' is indirectly accessed via method:
39+
string n = e.GetName();
40+
41+
// 'salary' is indirectly accessed via method:
42+
double s = e.GetSalary();
43+
}
44+
}
45+
```
46+

0 commit comments

Comments
 (0)