this Keyword
Overview
The this keyword refers to the object that is currently executing the code. However, its value is completely dynamic.
In most languages, this always points to the class it belongs to. In JavaScript, this is determined by HOW a function is called, not where it is defined.
If you call obj.func(), this is the object. But if you assign that function to a variable and just call func(), this suddenly becomes the global Window object (or undefined in Strict Mode)!
Syntax
const person = {
name: "Kartik",
sayHi: function() {
console.log(this.name); // 'this' points to 'person'
}
};
person.sayHi(); // Outputs: "Kartik"// We assign the function to a standalone variable
const looseFunction = person.sayHi;
// Because it was called without 'person.', context is lost!
looseFunction(); // Outputs: undefined!
// 'this' defaulted to the global window object!Common Pitfalls
- Using
thisinside a standard callback function (likesetTimeout). The callback is executed by the global timer, meaningthiswill point towindow. To fix this, you must use Arrow Functions, which 'lock in' the parent'sthiscontext.
Interview Questions
this determined in standard JavaScript functions?'this' is determined dynamically at runtime by the call-site (how the function is called). If it's called as a method obj.func(), it points to obj. If called standalone func(), it points to the global object.
this?Arrow functions do not bind their own this. They lexically capture the this value of their enclosing scope at the time they are defined.
Real-World Example
In legacy Class-based React components, developers had to manually bind this in the constructor for every single event handler, otherwise this.setState would throw an error.
this.handleClick = this.handleClick.bind(this);Check Your Knowledge
Test your understanding of this Keyword with these quick questions.