-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17-JSThis.js
More file actions
76 lines (63 loc) · 1.49 KB
/
17-JSThis.js
File metadata and controls
76 lines (63 loc) · 1.49 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
/*
* JavaScript this
*/
// 'use strict';
// “this” in Global Context
// console.log(this);
var firstName = 'Ali';
// “this” in Regular Functions
function myFunction() {
return this;
}
// console.log(myFunction());
//“this” in Arrow Functions
const myFunc = () => {
// console.log(this);
};
myFunc();
// “this” in Event Handlers
const myBtn = document.querySelector('button');
myBtn.addEventListener('click', function () {
console.log(this);
});
var fName = 'Shovo';
// let fName = 'Shovo';
// “this” in Methods of an Object
const student = {
fName: 'Ali',
sInfo: function () {
// console.log(`${student.fName} loves to read`);
return `${this.fName} loves to read`;
},
// Example using arrow function 👇
arrowFunction: () => {
return `${this.fName} loves to read`;
},
};
console.log(student.sInfo());
student.fName = 'Shovo';
console.log(student.sInfo());
console.log(student.arrowFunction());
/*
* The object that is exceuting the current function.
? Method 👉 object
? Function 👉 (Window, Global)
*/
function newPhone() {
let phone = 'Android';
console.log(this.phone);
}
newPhone();
const game = {
gName: 'NfS',
gInfo: function () {
console.log(`Love to play ${this.gName}`);
},
};
const aGame = {
gName: 'Car Game',
};
// The bind() method is used to create a new function with a specified value of “this” and initial arguments.
const bindGame = game.gInfo.bind(aGame);
console.log(game.gInfo());
console.log(bindGame());