-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththisKeyword.js
More file actions
41 lines (33 loc) · 1.04 KB
/
thisKeyword.js
File metadata and controls
41 lines (33 loc) · 1.04 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
"use strict";
console.log(this);
// In non-strict mode, "this" refers to the global object (window in browsers).
// In strict mode, "this" is undefined in the global context.
// "this" inside a function"
function abc() {
console.log(this);
}
abc();
// In non-strict mode, "this" refers to the global object (window in browsers).
// In strict mode, "this" is undefined because functions in strict mode don't automatically bind "this" to the global object.
// "this" inside an object's method"
const name1 = {
name: "Karan",
printName: function() {
console.log(this.name); // "this" refers to the object `name1`
}
};
name1.printName(); // Outputs "Karan" because "this" refers to `name1`
const name2 = {
name: "Satyam"
};
// Using the `call` method to override "this" context of `name1` with `name2`
name1.printName.call(name2);
// Outputs "Satyam" because "this" now refers to `name2` instead of `name1`
// "this" inside an arrow function
const obj = {
a: 567,
x: () => {
console.log(this);
}
};
obj.x();