|
1 | 1 | /*
|
2 |
| -🔹 3. this keyword |
3 |
| -✅ What is this? |
4 |
| -this refers to the object that is executing the current function. |
5 |
| -💡 Rule of Thumb: |
6 |
| -Context this refers to |
7 |
| -In a method: The object that owns the method |
8 |
| -Alone (non-strict): Global object (window) |
9 |
| -Alone (strict): undefined |
10 |
| -Inside an arrow function Inherits this from the surrounding lexical scope |
11 |
| -In event listener The element that received the event |
12 |
| -In constructor The newly created object |
| 2 | +INFO: What is this ? |
| 3 | +this refers to the context in which current code is running. |
| 4 | +It can points to: |
| 5 | +- an object |
| 6 | +- window in browser |
| 7 | +- undefined (in strict mode) |
| 8 | +- anything depending on how the function is called |
13 | 9 | */
|
| 10 | + |
| 11 | +/* |
| 12 | +1. this in a Method (object Context) |
| 13 | +When a function is called as a method of an object, this refers to that object. |
| 14 | +*/ |
| 15 | + |
| 16 | +const user = { |
| 17 | + name: "rafay", |
| 18 | + greet() { |
| 19 | + console.log(this.name); // "rafay" |
| 20 | + }, |
| 21 | +}; |
| 22 | +user.greet(); |
| 23 | + |
| 24 | +/* |
| 25 | +2. this in a Regular function |
| 26 | +In regular function (not a method), this behaves differently: |
| 27 | +*/ |
| 28 | +function show() { |
| 29 | + console.log(this); // window object |
| 30 | +} |
| 31 | +show(); |
| 32 | + |
| 33 | +/* |
| 34 | +3. this Used Alone |
| 35 | +When used alone outside of any function: |
| 36 | +*/ |
| 37 | +console.log(this); // window object |
| 38 | + |
| 39 | +/* |
| 40 | +4. this in Event handlers |
| 41 | +In DOM event handlers, this usually refers to the element that received the event. |
| 42 | +*/ |
| 43 | +const btn = document.querySelector("button"); |
| 44 | +btn.addEventListener("click", function () { |
| 45 | + console.log(this); // the button element <button>Click Me</button> |
| 46 | +}); |
| 47 | + |
| 48 | +/* |
| 49 | +5. this in Arrow Functions |
| 50 | +Arrow functions do not have their own this. They inherit it from their lexical (outer) scope. |
| 51 | +*/ |
| 52 | +const user1 = { |
| 53 | + name: "rafay", |
| 54 | + greet: function () { |
| 55 | + const inner = () => { |
| 56 | + console.log(this.name); // "rafay" |
| 57 | + }; |
| 58 | + inner(); |
| 59 | + }, |
| 60 | +}; |
| 61 | + |
| 62 | +user1.greet(); |
0 commit comments