Understanding "this" in JavaScript
Lahiru Sandaruwan
Javascript | Typescript | Angular | Node.js | Express.js | NestJS | Microservices | GraphQL | REST | KafkaJS | SQL | Git | GitHub | Microsoft PowerApps
In Javascript "this" is a keyword that behaves differently depending on the context in which it is used. Following are the main contexts and how "this" behaves in each.
Global Context
In the global execution context (outside of any function), "this" refers to the global object. In a web browser, this is the "window" object.
Regular Functions
In a regular function (not an arrow function), the value of "this" depends on how the function is called.
Arrow Functions
Arrow functions do not have their own "this". Instead, they inherit this from the enclosing lexical context (the function or global scope in which they are defined).
Constructor Functions and Classes
In constructor functions and class constructors, this refers to the newly created instance of the object.
Event Handlers
In DOM (Document Object Model) event handlers, this refers to the element that received the event.
Summary
"this" in JavaScript is context-dependent.
Understanding how "this" behaves in different contexts is crucial for writing effective and bug-free JavaScript code.
Application Developer @ DBS Bank - Java | ReactJS | Springboot | MySQL | Mongo | Kafka
5 个月Interesting!