Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
this is a keyword in JavaScript that points to the execution context of code. It's a reference to the object that "owns" the currently executing code or function. Importantly, the value of this can change depending on how the function was called.
When a function is called as an object method, this points to the object for which the method was called. That is, the value of this corresponds to the object before the dot when calling the function.
const obj = {
name: "hello",
getName: function() {
console.log(this.name);
}
};
obj.getName(); // will output "hello"
In arrow functions, this is not bound to the function itself like in regular functions, and they don't have their own this. Instead, this is determined when the arrow function is created and points to the parent context, that is, the context in which the arrow function was created.
const obj = {
name: "hello",
getName: () => {
console.log(this.name); // `this` points to global context (or window in browser)
}
};
obj.getName(); // will output undefined, because this is not bound to obj
In the case of classes, arrow functions behave differently. They preserve the this value from the context where the class was created. This allows using arrow functions inside classes for proper context binding.
Inside a class, an arrow function automatically binds this to the class instance, and the method will have access to properties of that instance.
class Example {
name = "hello";
getName = () => {
console.log(this.name); // here `this` points to class instance
};
}
new Example().getName(); // will output "hello"
Execution context is a special internal data structure that contains information about function call and includes:
this) won't be linked to object, but will be inherited from outer call context.const obj = {
name: "hello",
getName: () => {
console.log(this.name); // `this` points to global context
}
};
obj.getName(); // will output undefined, because `this` is not linked to object
Arrow Function Features:
Arrow functions don't have their own this context, and this can lead to unexpected results, especially in object methods.