-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfatArrow.js
More file actions
122 lines (89 loc) · 2.51 KB
/
fatArrow.js
File metadata and controls
122 lines (89 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
Why did JS introduce fat arrow syntax?
- shorter syntax.
- better handling of this. // Wooo! interesting!
( Assume a obj with a function as a property when you call that function it will have a scope of obj but if that function
has one more function defined inside it and you call it from outer function, the **this** inside inner function will be window.
This can be sorted using arrow functions.)
*/
// Shorter/Succinct syntax
// Traditional
function sum(a,b) {
return a + b;
}
// Fat Arrow way!
// const sum1 = (a, b) => a + b;
console.log(sum(10,20));
// console.log(sum1(10,20));
// Better handling of this.
let obj = {
name: 'Chen Yu Fei',
sayMyName: function() {
console.log(this);
},
sayMyNameLaterTraditional: function() {
setTimeout(function(){
console.log('In traditional ', this);
} , 1000);
},
sayMyNameLater: function() {
setTimeout(() => {
console.log('With Fat arrow later: ', this);
}, 1000)
},
sayMyNameFatArrow: () => {
console.log(this);
},
sayMyNameFat: (function() {
console.log(this);
}).bind(this)()
}
obj.sayMyName();
obj.sayMyNameLaterTraditional();
obj.sayMyNameLater(); // Fat arrow fixes the issue! Hurray!
obj.sayMyNameFatArrow(); // Gotcha!
obj.sayMyNameFat()
/*
Internals:
*/
let obj1 = {
name: 'Chen Yu Fei',
sayMyNameLater: function() {
setTimeout(() => {
console.log('With Fat arrow later: ', this);
}, 1000)
}
}
// ===
let internalObj1 = {
name: 'Chen Yu Fei',
sayMyNameLater: function() {
setTimeout( function() {
console.log('Traditional impl of fat arrow: ', this);
}.bind(this), 1000);
}
}
obj1.sayMyNameLater();
internalObj1.sayMyNameLater();
/*
What fat arrow does is, it takes the this where the function is defined and binds that to the function.
*/
// Pit fall of that.
let pitfallObj = {
name: 'Kadambi Srikanth',
sayMyNameLater: () => {
setTimeout(() => {
console.log('pitfallObj: ', this);
}, 2000);
}
}
pitfallObj.sayMyNameLater();
// Internals of pitfallObj
let internalPitfallObj = {
sayMyNameLater: function () {
setTimeout( function() {
console.log('Internal pitfallObj: ', this);
}.bind(this), 2000); // this was supposed to be internalPitfallObj, but overrode it to window by bind.
}.bind(this) // this here is window
}
internalPitfallObj.sayMyNameLater();