You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+29-3Lines changed: 29 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -8820,9 +8820,8 @@ multiplyBy2(add(2, 3));
8820
8820
**[⬆ Back to Top](#table-of-contents)**
8821
8821
8822
8822
452. ### What is the purpose of the this keyword in JavaScript?
8823
+
The `this` keyword in JavaScript refers to **the object that is executing the current function**. Its value is determined by **how a function is called**, not where it is defined. `this` is essential for writing object-oriented and event-driven code, as it allows methods to interact with the data of the object they belong to.
8823
8824
8824
-
- The `this` keyword in JavaScript is a special variable that is used within a function to refer to the object on which the function is invoked. The value of this depends on how the function is called. It allows functions to access and interact with the object they are bound to.
8825
-
- The this keyword in JavaScript is a reference to the object that owns or invokes the current function. Its value is determined by the calling context.
8826
8825
8827
8826
**Example 1: this in a Global Context**
8828
8827
@@ -8842,7 +8841,7 @@ multiplyBy2(add(2, 3));
8842
8841
displayThis();
8843
8842
```
8844
8843
8845
-
- In a regular function, this refers to the global object.
8844
+
- In a regular function, this refers to the global object(window in browser and global in nodejs) for non-strict mode. In strict mode, it's value is undefined.
8846
8845
8847
8846
**Example 3: this in a Method**
8848
8847
@@ -8869,6 +8868,33 @@ multiplyBy2(add(2, 3));
8869
8868
8870
8869
- In an event handler, this refers to the element that triggered the event (the button in this case).
8871
8870
8871
+
**Example 5: `this` with Arrow Functions**
8872
+
8873
+
```javascript
8874
+
constobj= {
8875
+
age:42,
8876
+
regular:function() { console.log(this.age); },
8877
+
arrow: () => { console.log(this.age); }
8878
+
};
8879
+
obj.regular(); // 42 (this refers to obj)
8880
+
obj.arrow(); // undefined (this refers to the outer scope, not obj)
8881
+
```
8882
+
- Arrow functions do not have their own `this` binding; they inherit it from their surrounding (lexical) context.
8883
+
8884
+
**Example 6: this in Constructor Functions / Classes**
8885
+
8886
+
```javascript
8887
+
functionPerson(name) {
8888
+
this.name= name;
8889
+
}
8890
+
8891
+
constp1=newPerson('Sudheer');
8892
+
console.log(p1.name); // Sudheer
8893
+
```
8894
+
- When used with new, this refers to the newly created object.
0 commit comments