this in JavaScript refers to the object that is currently calling a function.Its value is decided when the function runs, based on how it is called.

Common Meanings of this

  • Global scope → window (in browser)
  • Regular function

-Non-strict mode → window

-Strict mode → undefined

  • Object method → the object itself
  • Arrow function → inherits this from surrounding scope
  • Event handler → the HTML element
  • Class method → the class instance
  • call / apply / bind → this is explicitly set

1.Global Context

In Browser

console.log(this);

✔ Refers to the window object

this.alert("Hello");

In Strict Mode

"use strict";
console.log(this);

undefined

2.Inside a Function

Normal Function (Non-Strict)

function show() {
console.log(this);
}
show();

this → window

Strict Mode

"use strict";
function show() {
console.log(this);
}
show();

this → undefined

3.Inside an Object Method

const user = {
name: "Zaman",
greet() {
console.log(this.name);
}
};
user.greet(); // Zaman

 

this refers to the object before the dot

4.Method Borrowing Problem

const user1 = {
name: "Zaman",
greet() {
console.log(this.name);
}
};
const greet = user1.greet;
greet(); // undefined

this lost context

5.Arrow Functions (Very Important)

Arrow functions do not have their own this
They inherit this from parent scope

const user = {
name: "Zaman",
greet: () => {
console.log(this.name);
}
};
user.greet(); // undefined

 

❌ Do NOT use arrow functions as object methods

Arrow Function Inside Method (Correct Use)

const user = {
name: "Zaman",
greet() {
const inner = () => {
console.log(this.name);
};
inner();
}
};
user.greet(); // Zaman

6.Constructor Functions & Classes

function User(name) {
this.name = name;
}
const u1 = new User("Zaman");
console.log(u1.name); // Zaman

this → newly created object

Class Example

class Car {
constructor(brand) {
this.brand = brand;
}
}

7.Event Handlers

Normal Function

button.addEventListener("click", function () {
console.log(this);
});

this → element clicked

Arrow Function

button.addEventListener("click", () => {
console.log(this);
});

this → window (or parent scope)

Categorized in:

Javascript,