DEV Community

Mofijul Haque
Mofijul Haque

Posted on

"this" keyword in JavaScript

In Regular Function

In JavaScript, when an object method is invoked, the "this" keyword inside the method refers to the object that the method is a property of.

For Example

let obj = {
name: "John",
sayName: function() {
console.log(this.name);
}
};
obj.sayName(); // Output: "John"

Here the 'sayName' method is a property of the 'obj' object, and when it's invoked, 'this' inside the method refers to 'obj', so 'this.name' evaluates to "John".

In Arrow Function

// In JavaScript, arrow functions do not have their own "this" value. Instead, they inherit the "this" value from the surrounding scope.

For example:

`
let obj = {
name: 'John',
sayName: () => {
console.log(this.name);
}
};

obj.sayName(); // undefined (instead of "John")

`
In the example above, the arrow function 'sayName' is a method of the 'obj' object. However, because the arrow function does not have its own "this" value, it inherits the "this" value from the global scope, which is undefined instead of the 'obj' object.

This can be overcome by using the bind() method to explicitly bind the this value to the object
`

let obj1 = {
name: 'John',
sayName: function () {
console.log(this.name);
}
};

let arrowSayName = obj1.sayName.bind(obj1);
arrowSayName()// 'John'
`

It's important to note that the value of "this" can be reassigned using bind, call, or apply methods or if the method is passed as a callback function and invoked in a different context.

In addition, when a constructor function is used to create an object, the "this" keyword inside the constructor function refers to the new object that is being created.

'this' is a powerful tool in javascript to access the context of the function, but it can be tricky to understand and use it correctly, and it's important to keep in mind the context of the function and how it is invoked to avoid unexpected results.

It's important to understand the behavior of this keyword when it comes to arrow functions because it can lead to unexpected results and bugs in your code if you're not careful.

Top comments (0)