Understanding this in JavaScript

📌 What is this?

In JavaScript, the this keyword refers to the context in which a function is executed. Its value depends on how a function is called, not where it’s defined. 🧠

Note

Unlike other languages, this in JavaScript is dynamic and often confusing to beginners. Let’s demystify it!

📦 Global Context

In the global scope (outside any function), this refers to the global object:

Global this

console.log(this); // In browser: window

👨‍💼 In Regular Functions

In non-strict mode, inside a regular function, this refers to the global object. In strict mode, it's undefined.

this in Regular Function

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

showThis(); // window (non-strict), undefined (strict)

Note

Use "use strict" to see how this behaves differently.

🧱 In Object Methods

When a function is called as a method of an object, this refers to that object.

this in Object Method

const user = {
  name: "Alice",
  greet() {
    console.log("Hello, " + this.name);
  }
};

user.greet(); // Hello, Alice

📌 Arrow Functions

Arrow functions do not have their own this. Instead, they capture this from the surrounding (lexical) scope.

this in Arrow Function

const user = {
  name: "Bob",
  greet: () => {
    console.log("Hi, " + this.name);
  }
};

user.greet(); // Hi, undefined (because 'this' is not user)

Note

Arrow functions are great for callbacks but not suitable when you need dynamic this.

💡 In Constructor Functions

In constructor functions (functions called with new), this refers to the newly created object.

this in Constructor Function

function Person(name) {
  this.name = name;
}

const p = new Person("Charlie");
console.log(p.name); // Charlie

🔁 With call, apply, and bind

You can manually control what this points to using call(), apply(), or bind().

call / apply / bind

function sayHi() {
  console.log("Hi " + this.name);
}

const user = { name: "Diana" };

sayHi.call(user);  // Hi Diana
sayHi.apply(user); // Hi Diana

const boundHi = sayHi.bind(user);
boundHi();         // Hi Diana

🚨 Common Mistakes

  • Forgetting context when passing methods as callbacks
  • Using arrow functions where dynamic this is needed
  • Confusion between global and object contexts

🧪 Test Yourself

Quick Quiz

const obj = {
  num: 42,
  getNum: function() {
    return this.num;
  }
};

const get = obj.getNum;
console.log(get()); // ❓

Note

In the quiz above, get is called in global context, so this will not refer to obj.

📚 Further Reading

>>“Understanding this is a rite of passage in JavaScript mastery.” – Every JavaScript Developer Ever 🚀