DEV Community

Mofijul Haque
Mofijul Haque

Posted on

1

"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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more