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
Copy file name to clipboardExpand all lines: README.md
+77Lines changed: 77 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -43,3 +43,80 @@ This bug highlights that we need to be careful when refactoring legacy code whic
43
43
44
44
> **Best Practice**: Leave **var** declarations inside of legacy code to denote that it needs to be carefully refactored. When working on a new codebase, use **let** for variables that will change their value over time, and **const** for variables that will be immutable over time.
45
45
46
+
## Replacing IIFEs with Blocks
47
+
48
+
> A common use of **Immediately Invoked Function Expressions** is to enclose values within its scope. In ES6, we now have the ability to create block-based scopes and therefore are not limited purely to function-based scope.
49
+
50
+
```javascript
51
+
(function () {
52
+
var food ='Meow Mix';
53
+
}());
54
+
console.log(food); // Reference Error
55
+
```
56
+
57
+
Using ES6 Blocks:
58
+
59
+
```javascript
60
+
{
61
+
let food ='Meow Mix';
62
+
}
63
+
console.log(food); // Reference Error
64
+
```
65
+
66
+
## Arrow Functions
67
+
68
+
Often times we have nested functions in which we would like to preserve the context of **this** from it's lexical scope. An example is shown below:
69
+
70
+
```javascript
71
+
functionPerson(name) {
72
+
this.name= name;
73
+
}
74
+
75
+
Person.prototype.prefixName=function (arr) {
76
+
returnarr.map(function (character) {
77
+
returnthis.name+ character; // Cannot read property 'name' of undefined
78
+
});
79
+
};
80
+
```
81
+
82
+
One common solution to this problem is to store the context of **this** using a variable:
83
+
84
+
```javascript
85
+
functionPerson(name) {
86
+
this.name= name;
87
+
}
88
+
89
+
Person.prototype.prefixName=function (arr) {
90
+
var that =this; // Store the context of this
91
+
returnarr.map(function (character) {
92
+
returnthat.name+ character;
93
+
});
94
+
};
95
+
```
96
+
97
+
Using **Arrow Functions**, the lexical value of **this** isn't shadowed and we can re-write the above as shown:
0 commit comments