1
+ // 5. This
2
+
3
+ const user = {
4
+ username : "Ayush" ,
5
+ price : 999 ,
6
+ welcomeMessage : function ( ) {
7
+ console . log ( `${ this . username } , welcome to website.` ) ;
8
+ // Note: While referring current context we use 'this' keyword.
9
+ console . log ( this ) ; // Note: Will print the current context.
10
+ }
11
+ }
12
+ // user.welcomeMessage() // Output: Ayush, welcome to website.
13
+ // user.username = "sam"
14
+ // user.welcomeMessage() // Output: sam, welcome to website.
15
+
16
+ console . log ( this ) ; // Output: {} Prints an empty object.
17
+ // Note: When we run this in browser's console we get window global object.
18
+
19
+ function one ( ) {
20
+ console . log ( this ) ;
21
+ }
22
+ // one() // Output: We get many values
23
+
24
+ function two ( ) {
25
+ let username = "ayush"
26
+ console . log ( this . username ) ;
27
+ }
28
+ // two() // Output: Undefined
29
+
30
+ const three = function ( ) {
31
+ let username = "sam"
32
+ console . log ( this . username ) ;
33
+ }
34
+ // three() // Output: undefined
35
+
36
+ /* ---------------------------------------------------------------------------
37
+ Arrow Function, */
38
+
39
+ const chai = ( ) => { // It's an arrow function
40
+ let name = "Ayush"
41
+ console . log ( this . username ) ;
42
+ }
43
+ chai ( ) // Output: undefined
44
+ // Note: If in arrow function we do console.log(this) then we get empty {}
45
+
46
+ // Explicit Return
47
+ const addTwo = ( num1 , num2 ) => {
48
+ return num1 + num2
49
+ }
50
+ console . log ( addTwo ( 3 , 4 ) ) // Output: 7
51
+
52
+ // Implicit Return,
53
+ const add = ( num1 , num2 ) => ( num1 + num2 )
54
+ console . log ( add ( 3 , 4 ) ) ; // Output: 7
55
+
56
+ /* Note: When using curly braces {} then we have use return keyword and when
57
+ using parenthesis () then we don't have to use return keyword. */
58
+
59
+ const returnObject = ( ) => ( { username : "ayush" } )
60
+ console . log ( returnObject ( ) ) // Output: { username: 'ayush' }
0 commit comments