-
Notifications
You must be signed in to change notification settings - Fork 125
/
this.js
50 lines (40 loc) · 1.27 KB
/
this.js
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
//Global Context:
console.log(this); // In the browser, this will log the window object.
// Object Method:
let task = {
title: "Buy groceries",
isCompleted: false,
toggleCompletion: function() {
console.log(this); // Logs the task object.
this.isCompleted = !this.isCompleted;
}
};
task.toggleCompletion(); // `this` refers to the `task` object.
console.log(task.isCompleted); // Output: true
// Function Context:
function showGlobalThis() {
console.log(this); // In non-strict mode, logs the global object (window).
}
showGlobalThis();
// show html file Event Handlers
// Constructor Functions:
function Task(title) {
this.title = title;
this.isCompleted = false;
}
let myTask = new Task("Buy groceries");
console.log(myTask.title); // Output: Buy groceries
// Arrow Functions:
let tasks = {
title: "Buy groceries",
isCompleted: false,
toggleCompletion: function() {
let innerFunction = () => {
console.log(this); // `this` refers to the `task` object.
this.isCompleted = !this.isCompleted;
};
innerFunction();
}
};
tasks.toggleCompletion(); // `this` refers to the `task` object.
console.log(tasks.isCompleted); // Output: true