Skip to content

Commit d3d105b

Browse files
committed
this keyword in javascript
1 parent 19cdf5e commit d3d105b

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

README.md

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8820,9 +8820,8 @@ multiplyBy2(add(2, 3));
88208820
**[⬆ Back to Top](#table-of-contents)**
88218821
88228822
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.
88238824
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.
88268825
88278826
**Example 1: this in a Global Context**
88288827
@@ -8842,7 +8841,7 @@ multiplyBy2(add(2, 3));
88428841
displayThis();
88438842
```
88448843
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.
88468845
88478846
**Example 3: this in a Method**
88488847
@@ -8869,6 +8868,33 @@ multiplyBy2(add(2, 3));
88698868
88708869
- In an event handler, this refers to the element that triggered the event (the button in this case).
88718870
8871+
**Example 5: `this` with Arrow Functions**
8872+
8873+
```javascript
8874+
const obj = {
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+
function Person(name) {
8888+
this.name = name;
8889+
}
8890+
8891+
const p1 = new Person('Sudheer');
8892+
console.log(p1.name); // Sudheer
8893+
```
8894+
- When used with new, this refers to the newly created object.
8895+
8896+
8897+
88728898
**[⬆ Back to Top](#table-of-contents)**
88738899
88748900
453. ### What are the uses of closures?

0 commit comments

Comments
 (0)