Preparing your workspace
The value of this depends on how a function is called, while arrow functions capture this from their surrounding lexical scope.
this is a special value in JavaScript that refers to a context determined by the way a function is invoked. When a method is called through an object, this commonly refers to that object. The value can also be controlled using call, apply, and bind. Arrow functions behave differently because they do not create their own this; they capture it from the surrounding scope. Understanding this is important when working with objects, classes, callbacks, and event-driven code.
A class method may use this to access the current object's properties, while an arrow callback can preserve the surrounding this value.
const student = {
name: 'Aman',
greet() {
console.log(`Hello, ${this.name}`);
}
};
student.greet();The console prints 'Hello, Aman'.