-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path061-arrow-fn-this.js
More file actions
84 lines (68 loc) · 1.6 KB
/
061-arrow-fn-this.js
File metadata and controls
84 lines (68 loc) · 1.6 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
// 1: THE KEY DIFFERENCE
// const person = {
// name: 'Alice',
// greet: function() {
// console.log('Hello, I am ' + this.name);
// }
// };
// person.greet(); // Output: Hello, I am Alice
const person = {
name: 'Alice',
greet: () => {
console.log('Hello, I am ' + this.name);
}
};
person.greet(); // Output: Hello, I am undefined
// 2: WHERE ARROW FUNCTIONS SHINE
const counter = {
count: 0,
start: function() {
setInterval(() => {
this.count++;
console.log(this.count);
}, 1000);
}
};
counter.start(); // Output: 1, 2, 3....
const team = {
members: ['John', 'Sarah', 'Mike'],
teamName: 'Developers',
showTeam: function() {
this.members.forEach((member) => {
console.log(member + ' is part of ' + this.teamName);
});
}
};
team.showTeam();
// Output:
// John is part of Developers
// Sarah is part of Developers
// Mike is part of Developers
// 3: IMPORTANT LIMITATIONS
const Person = (name) => {
this.name = name;
};
const john = new Person('John'); // Error!
const sum = (...numbers) => {
return numbers.reduce((total, num) => total + num, 0);
};
console.log(sum(1, 2, 3, 4)); // Output: 10
const arrowFunc = () => console.log(this);
const obj = { name: 'Test' };
arrowFunc.call(obj); // 'this' is NOT changed
// 4: QUICK GUIDELINES
// ✅ Good
// const numbers = [1, 2, 3];
// const doubled = numbers.map(n => n * 2);
// // ❌ Bad
// const calculator = {
// value: 0,
// add: (n) => this.value += n // Won't work!
// };
// // ✅ Correct
// const calculator = {
// value: 0,
// add: function(n) {
// this.value += n;
// }
// };