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
Unlike regular functions, arrow functions do not have their own **this**.
2
+
3
+
```js
4
+
let user = {
5
+
name:"GFG",
6
+
gfg1: () => {
7
+
console.log("hello "+**this**.name) // no '**this**' binding here
8
+
},
9
+
gfg2() {
10
+
console.log("Welcome to "+**this**.name) // '**this**' binding works here
11
+
},
12
+
}
13
+
user.gfg1() // => undefined
14
+
user.gfg2() // 'Welcome to GFG'
15
+
```
16
+
17
+
You cannot rebind **this**. in an arrow function. It will always be defined as the context in which it was defined. If you require \***\*this\*\*** to be meaningful you should use a normal function.
18
+
19
+
From the ECMAScript 2015 Spec:
20
+
21
+
Any reference to arguments, super, **this**, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically **this** will be the Function Environment of an immediately enclosing function.
22
+
23
+
**this** inside an arrow function always 'inherits' the **this** from the enclosing scope. That is a feature of arrow functions. But you can still bind all other parameters of an arrow function. Just not **this**
24
+
25
+
You cannot bind a value since the **this** is already binded.
Regular functions created using function declarations or expressions are ‘constructible’ and ‘callable’. Since regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible. Thus, we will get a run-time error on trying to construct a non-constructible arrow functions using the new keyword.
# Arrow functions are cool in ES6. When should you NOT use arrow functions. Name three or more cases.
1
+
###Arrow functions are cool in ES6. When should you NOT use arrow functions. Name three or more cases.
2
2
3
-
Arrow functions are neat but are not suitable for all use cases. For those who are ready to get rid of `function` and move on to arrow functions, it's time to examine a simple scenario where the arrow function would complicate your logic.
4
-
5
-
## 1. Event Handlers
3
+
### 1. Event Handlers
6
4
7
5
Let's look at this example, we have a link on our page with an id of `myLink`. Every time you hover over this link, a CSS class `highlight` is toggled and the text is highlighted.
8
6
9
7
```js
10
-
var myLink =document.getElementById('myLink');
11
-
myLink.addEventListener('mouseenter', function(){
12
-
this.classList.toggle('highlight');
13
-
console.log(this.classList);
14
-
});
8
+
var myLink =document.getElementById("myLink")
9
+
myLink.addEventListener("mouseenter", function(){
10
+
this.classList.toggle("highlight")
11
+
console.log(this.classList)
12
+
})
15
13
```
14
+
16
15
This logs `highlight`.
17
16
18
17
Using ES6 syntax, this works as expected. Now let's try that in ES6 using arrow functions:
19
18
20
19
```js
21
-
constmyLink=document.getElementById('myLink');
22
-
myLink.addEventListener('mouseenter', () => {
23
-
this.classList.toggle('hightlight');
24
-
console.log(this.classList);
25
-
});
20
+
constmyLink=document.getElementById("myLink")
21
+
myLink.addEventListener("mouseenter", () => {
22
+
this.classList.toggle("hightlight")
23
+
console.log(this.classList)
24
+
})
26
25
```
27
-
This logs `TypeError: Cannot read property 'classList' of undefined`.
28
-
29
-
If you use an arrow function, the keyword ``this`` is not bound to that element. If we use a regular function, the keyword this will be bound to the element we clicked!
30
-
31
-
32
-
33
-
If you're not sure whether an arrow function is appropriate, [Kyle Simpson](https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch2.md) provides us with this awesome chart:
This logs `TypeError: Cannot read property 'classList' of undefined`.
36
28
29
+
When using an arrow function `this` is not bound to anything and it just inherits it from the parent scope which may be window. If we use a regular function, the keyword 'this' will be bound to the element we clicked. Remember,
37
30
38
31
## 2: Object Methods
39
32
40
33
```js
41
34
constperson= {
42
-
points:23,
43
-
score: () => {
44
-
returnthis.points++;
45
-
}
35
+
points:23,
36
+
score: () => {
37
+
returnthis.points++
38
+
},
46
39
}
47
40
48
-
person.score();
41
+
person.score()
49
42
50
-
console.log(person.points) // it ouputs 23 irrepective of howmany times i run the above block of code
43
+
console.log(person.points) // it outputs 23 irrespective of how many times i run the above block of code instead of getting incremented by earlier call of person.score().
51
44
```
45
+
52
46
We have our method called score, and whenever we call person.score, it should add one to our points, which is currently 23.
53
47
54
48
If we run person.score(); a few times, we should be at 26 or something.
55
49
56
-
But if I call person, points is still at 23. Why?
50
+
But if I call person.points is still at 23. Why?
57
51
58
52
Because it’s trying to add points to the window! Remember, when using an arrow function this is not bound to anything and it just inherits it from the parent scope which in this case is the window.
59
53
@@ -71,4 +65,5 @@ person.score();
71
65
72
66
console.log(person.points)
73
67
```
74
-
And now, first output is 24 and then 25 and so on..
68
+
69
+
And now, first output is 24 and then 25 and so on..
Copy file name to clipboardExpand all lines: Javascript/call-apply-bind/call-function-basics-2.md
+23-1
Original file line number
Diff line number
Diff line change
@@ -26,9 +26,31 @@ f() // => 10
26
26
f.call(o) // => 15
27
27
```
28
28
29
+
### Very Importantly note, the call() method as above will NOT work in arrow function. And this.x will produce undefined. Because, Unlike regular functions, arrow functions do not have their own 'this'
30
+
31
+
```js
32
+
global.x=10
33
+
34
+
constobj= {
35
+
x:15,
36
+
func: () =>console.log(this.x),
37
+
func2:function() {
38
+
console.log(this.x)
39
+
},
40
+
}
41
+
42
+
constfunc= () =>console.log(this.x)
43
+
44
+
func() // => undefined
45
+
func.call(obj) // => undefined
46
+
obj.func.call(obj) // => undefined
47
+
// But the following will work as expected
48
+
obj.func2.call(obj) // => 15, accessing the
49
+
```
50
+
29
51
The first invocation of f() will display the value of 10, because this references the global object. The second invocation (via the call method) however, will display the value 15. 15 is the value of the x property inside object o.
30
52
31
-
### The call() method invokes the function and uses its first parameter as the this pointer inside the body of the function. In other words - we've told the runtime what object to reference as this while executing inside of function f().
53
+
### The call() method invokes the function and uses its first parameter as the this pointer inside the body of the function. In other words - we've told the runtime what object to reference as 'this' while executing inside of function f().
32
54
33
55
### The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.
Copy file name to clipboardExpand all lines: Javascript/curried-function.md
+4
Original file line number
Diff line number
Diff line change
@@ -1,3 +1,7 @@
1
+
#### Is a technique for converting function calls with N arguments into chains of N function calls with a single argument for each function call?
2
+
3
+
#### Currying always returns another function with only one argument until all of the arguments have been applied. So, we just keep calling the returned function until we’ve exhausted all the arguments and the final value gets returned.
Copy file name to clipboardExpand all lines: Javascript/js-basics/this-keyword.js
+33-33
Original file line number
Diff line number
Diff line change
@@ -3,68 +3,68 @@
3
3
4
4
Inside a function, the value of this depends on how the function is called.
5
5
6
-
Case-1 - WITHOUT STRICT MODE - Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.
6
+
Case-1 - WITHOUT STRICT MODE - If a function is not in strict mode, and if the value of this is not set by the call, this will default to the global object, which is window in a browser.
7
7
8
-
Case-2 - In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, so, in the following case, this will default to undefined. So, in strict mode, if this was not defined by the execution context, it remains undefined.
8
+
Case-2 - In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, 'this' will default to undefined. So, in strict mode, if this was not defined by the execution context, it remains undefined.
9
9
10
10
*/
11
11
12
12
// Case-1 - WITHOUT STRICT MODE - Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.
13
13
14
14
functionf1(){
15
-
returnthis;
15
+
returnthis
16
16
}
17
17
18
18
// In a browser:
19
-
f1()===window;// true
19
+
f1()===window// true
20
20
21
21
// In Node:
22
-
f1()===global;// true
22
+
f1()===global// true
23
23
24
24
// Case-2 - In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, so, in the following case, this will default to undefined. So, in strict mode, if this was not defined by the execution context, it remains undefined.
25
25
26
26
functionf2(){
27
-
"use strict";// see strict mode
28
-
returnthis;
27
+
"use strict"
28
+
returnthis
29
29
}
30
30
31
-
f2()===undefined;// true
31
+
f2()===undefined// true
32
32
33
33
// In the Case-2 above, `this` was returned to be undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()).
34
34
35
35
// To pass the value of this from one context to another, use call(), or apply():
36
36
37
37
// An object can be passed as the first argument to call or apply and this will be bound to it.
38
-
varobj={a: "Custom"};
38
+
varobj={a: "Custom"}
39
39
40
40
// This property is set on the global object
41
-
vara="Global";
41
+
vara="Global"
42
42
43
43
functionwhatsThis(){
44
-
returnthis.a;// The value of this is dependent on how the function is called
44
+
returnthis.a// The value of this is dependent on how the function is called
45
45
}
46
46
47
-
whatsThis();// 'Global'
48
-
whatsThis.call(obj);// 'Custom'
49
-
whatsThis.apply(obj);// 'Custom'
47
+
whatsThis()// 'Global'
48
+
whatsThis.call(obj)// 'Custom'
49
+
whatsThis.apply(obj)// 'Custom'
50
50
51
51
/* Where a function uses the 'this' keyword in its body, its value can be bound to a particular object in the call using the call() or apply() methods which all functions inherit from Function.prototype. */
52
52
53
53
functionadd(c,d){
54
-
returnthis.a+this.b+c+d;
54
+
returnthis.a+this.b+c+d
55
55
}
56
56
57
-
varo={a: 1,b: 3};
57
+
varo={a: 1,b: 3}
58
58
59
59
// The first parameter is the object to use as
60
60
// 'this', subsequent parameters are passed as
61
61
// arguments in the function call
62
-
add.call(o,5,7);// 16
62
+
add.call(o,5,7)// 16
63
63
64
64
// The first parameter is the object to use as
65
65
// 'this', the second is an array whose
66
66
// members are used as the arguments in the function call
@@ -76,23 +76,23 @@ B) By default the execution context for an execution is global which means that
76
76
“window” object is the global object in case of browser and in Node.JS environment, a special object “global” will be the value of “this”.
77
77
*/
78
78
79
-
global.a=2;
79
+
global.a=2
80
80
81
81
functionfoo(){
82
-
returnthis.a;
82
+
returnthis.a
83
83
}
84
84
85
-
console.log(foo());// => 2
85
+
console.log(foo())// => 2
86
86
87
87
// SECOND TEST CASE
88
88
89
-
varb=2;
89
+
varb=2
90
90
91
91
functionfoo1(){
92
-
console.log(this.b);
92
+
console.log(this.b)
93
93
}
94
94
95
-
foo1();// => 'undefined'
95
+
foo1()// => 'undefined'
96
96
97
97
// Explanation of the above - I got 'undefined' because in VS-Code here, I am in node environment so just declaring var b = 2 will not attach the variable to the 'global' environment of vs-code
98
98
@@ -101,24 +101,24 @@ When an Object’s method is invoked then “this” refers to the object which
101
101
102
102
varobj={
103
103
c: 3,
104
-
foo3: foo3
105
-
};
104
+
foo3: foo3,
105
+
}
106
106
107
107
functionfoo3(){
108
-
console.log(this.c);
108
+
console.log(this.c)
109
109
}
110
-
obj.foo3();// => 3
110
+
obj.foo3()// => 3
111
111
112
112
// FOURTH TEST CASE
113
113
functionfoo4(){
114
-
console.log(this===global);
114
+
console.log(this===global)
115
115
}
116
-
foo4();// => true
116
+
foo4()// => true
117
117
118
118
// FIFTH TEST CASE - If strict mode is enabled for any function then the value of “this” will be “undefined” as in strict mode, global object refers to undefined in place of windows object.
0 commit comments