this Keyword
In JavaScript, the this keyword is a special identifier that refers to the context in which a piece of code is being executed.
In simple terms, this refers to the object that is currently executing the code.
But — here’s the tricky part — the value of this depends on how and where the function is called, not where it is written.
Let’s break that down step by step.
What Is this?
The this keyword provides a way to access the current execution context — the “owner” of the function.
Think of it like this:
If a person (object) is performing an action (method),
thisrefers to that person (the object).
Example 1: this in an Object Method
When a function is called as a method of an object, this refers to that object.
let person = {
name: "Harry",
greet: function() {
console.log("Hi, my name is " + this.name);
}
};
person.greet(); // Output: Hi, my name is HarryHere, this.name refers to person.name because the greet method is owned by the person object.
Example 2: this in a Regular Function (Global Context)
When this is used outside of any object, it refers to the global object.
- In browsers, the global object is
window. - In Node.js, it’s
global.
console.log(this); // In browser: Window {...}If you use this inside a regular function, it also defaults to the global object (in non-strict mode).
function showThis() {
console.log(this);
}
showThis(); // Output: Window (in browser)However, in strict mode (
'use strict'),thiswill beundefinedinside regular functions.
Example 3: this Inside a Method vs. a Function
Let’s see how this can behave differently depending on how the function is called:
let car = {
brand: "Tesla",
showBrand: function() {
console.log(this.brand);
}
};
car.showBrand(); // Output: Tesla
let display = car.showBrand;
display(); // Output: undefined (or error in strict mode)Why did the second one fail?
Because when we stored car.showBrand in display, it lost its reference to the car object.
Now it’s just a normal function — so this points to the global object, not car.
Example 4: this in Arrow Functions
Arrow functions work differently!
They don’t have their own this — instead, they inherit this from their lexical scope (the environment in which they were defined).
Example:
let user = {
name: "Riya",
greet: () => {
console.log("Hi, " + this.name);
}
};
user.greet(); // Output: Hi, undefinedHere, the arrow function doesn’t bind its own this, so it takes it from the outer (global) scope — where this.name is undefined.
Correct Way with a Normal Function
let user = {
name: "Riya",
greet: function() {
console.log("Hi, " + this.name);
}
};
user.greet(); // Output: Hi, RiyaSo remember:
Arrow functions are great for callbacks, but not ideal for methods that need their own
this.