Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 7: The ‘this’ Keyword & Context

1. What is ‘this’?

The this keyword is a reference to an Execution Context object. Its value is determined dynamically at the moment the function is executed.

There are 4 Rules of Binding that determine what this points to.


2. Rule 1: Default Binding (Global Context)

If a function is called as a standalone function, this refers to the global object.

  • In Browser: window
  • In Strict Mode: undefined (Strict mode prevents accidental global variable creation).

JavaScript

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

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

3. Rule 2: Implicit Binding (Object Method)

When a function is called as a method of an object, this points to the object that is standing before the dot.

JavaScript

const user = {
    name: "Gemini",
    greet: function() {
        console.log(`Hello, I am ${this.name}`);
    }
};

user.greet(); // "this" is 'user'. Output: "Hello, I am Gemini"

Warning: If you copy the method to a variable and call it, you lose the binding!

JavaScript

const looseGreet = user.greet;
looseGreet(); // Error or undefined! "this" is now back to Default Binding.

4. Rule 3: Explicit Binding (call, apply, bind)

What if you want to force this to point to a specific object? JavaScript gives us three tools:

A. .call()

Invokes the function immediately and passes arguments one by one.

B. .apply()

Invokes the function immediately and passes arguments as an array.

C. .bind()

Does not invoke the function. Instead, it returns a new function with this permanently locked to the object.

JavaScript

const person1 = { name: "Alice" };
const person2 = { name: "Bob" };

function introduce(skill, city) {
    console.log(`${this.name} knows ${skill} and lives in ${city}`);
}

introduce.call(person1, "JavaScript", "New York");
introduce.apply(person2, ["Python", "London"]);

const bobIntro = introduce.bind(person2, "Cooking", "Paris");
bobIntro(); 

5. Rule 4: New Binding (Constructor Functions)

When a function is called with the new keyword, this refers to the brand new object being created.

JavaScript

function Car(model) {
    this.model = model;
}

const myCar = new Car("Tesla");
console.log(myCar.model); // "Tesla"

6. The Arrow Function Exception

Arrow functions do not have their own this. They inherit this from their surrounding (lexical) scope. This makes them perfect for callbacks and timers where you don’t want the context to change.

JavaScript

const group = {
    title: "Developers",
    members: ["Alice", "Bob"],
    showMembers() {
        // Regular function inside forEach would lose "this"
        // Arrow function inherits "this" from showMembers()
        this.members.forEach((member) => {
            console.log(`${this.title}: ${member}`);
        });
    }
};

group.showMembers();

💻 Technical Code Example: Common Interview Trap

Question: What will the following code output?

JavaScript

const obj = {
    msg: "Secret",
    print: function() {
        setTimeout(function() {
            console.log(this.msg);
        }, 100);
    }
};

obj.print(); 

Answer: undefined. Why? setTimeout is a Web API that calls the inner function separately. By the time it runs, the “Implicit Binding” to obj is lost, and it falls back to “Default Binding” (the window). The Fix: Use an Arrow Function inside setTimeout, or use .bind(this).

In Simple words :

1. Introduction

In many bugs and interview questions, one word appears again and again:

👉 this

Understanding this is about understanding:

  • Who is calling the function
  • In which context the code is executed

2. What is this?

Definition

this is a special reference variable that points to the current execution context.

In simple terms:

this refers to the object that is currently executing the code.

⚠️ The value of this is not fixed — it depends on how a function is called, not where it is written.


3. Execution Context

What is Context?

Context means the environment in which code is executed.

It defines:

  • Value of this
  • Access to variables
  • Scope chain

4. Types of Execution Context

  1. Global Execution Context
  2. Function Execution Context
  3. Object / Method Context
  4. Constructor Context
  5. Lexical Context (Arrow Functions)

5. this in Global Context

JavaScript

  • In browser → this refers to window
  • In Node.js → this refers to an empty object {}

Example:

this === window  // true (browser)

Java / C++

  • No global this
  • this exists only inside class methods

6. this Inside a Function

Regular Function Call

In JavaScript:

  • thisundefined (strict mode)
  • this → global object (non-strict)

Example:

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

Key Rule

Function call decides this, not function definition


7. this Inside an Object (Method Context)

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

Example:

user.printName()

Here:

this → user

8. this Inside a Constructor

Constructor Context

When using new keyword:

  • this refers to the newly created object

Example:

new User("Prakash")

this → new User instance


9. this in Arrow Functions

Key Rule

Arrow functions do not have their own this.

They inherit this from their lexical (outer) scope.

Example:

() => {
   console.log(this)
}

Useful for:

  • Callbacks
  • Event handlers
  • Closures

10. this in Event Handlers

Regular Function

this → element that triggered the event

Arrow Function

this → outer scope

This is a very common interview question.


11. Explicit Binding of this

JavaScript allows manual control of this.

call()

Calls function with specified this.


apply()

Same as call, but arguments passed as array.


bind()

Returns a new function with permanently bound this.


12. this in Class-Based Languages

Java / C++

  • this refers to current object
  • Used to resolve naming conflicts
  • Pass current object as parameter

Example use cases:

  • Constructor parameters
  • Method chaining

13. this vs self (Python)

  • Python uses self
  • Explicit parameter
  • Works similarly to this

Example:

self.name = name

14. Common this Pitfalls

  • Losing context in callbacks
  • Using arrow functions incorrectly
  • Assuming this behaves same in all languages
  • Confusing scope with context

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥