Explorer
JavaScript

The "this" Keyword

1. The Story Behind this: The Microphone and the Pronoun "I"

Imagine a meeting where only the person holding the microphone can speak.

The CEO picks up the microphone and says:

"I'm responsible for this company."

Here, "I" refers to the CEO.

A few minutes later, an intern picks up the same microphone and says:

"I'm responsible for this company."

Now, "I" refers to the intern.

The microphone hasn't changed. The person holding it has.

JavaScript's this keyword works in a similar way.

For regular functions, the value of this is generally determined by how the function is called, not where the function was originally written.

Look at this example:

JAVASCRIPT
const user = {
  name: "Alex",

  greet() {
    console.log(this.name);
  }
};

user.greet(); // Alex

When we call user.greet(), the object before the dot is user. Therefore, this refers to user.

But what happens if we take the same function and call it separately?

JAVASCRIPT
//also known as detached function
const greet = user.greet;

greet();

We have extracted the function from the object. The function itself hasn't changed, but the way we invoke it has.

That is the central idea behind this.

Remember: For regular functions, look at the call site to understand what this refers to.

2. The Global Execution Context, window, and this

Before exploring the different binding rules, we need to understand what happens when JavaScript runs a program.

Consider an empty JavaScript file.

Even if there is no code inside it, the JavaScript engine still initializes the environment required to execute JavaScript.

This is commonly explained through the Global Execution Context (GEC).

At the global level, JavaScript provides a global object and a global this value. However, the exact behavior depends on the environment and whether the code runs as a classic script or an ES module.

The global object

In different JavaScript environments, the global object has different names:

  • Browser: window (also accessible through globalThis).

  • Node.js: global (also accessible through globalThis).

  • Modern JavaScript: globalThis provides a standard way to access the global object.

For example, in a browser's classic script:

JAVASCRIPT
console.log(this === window); // true
console.log(globalThis === window); // true

At the top level of a browser classic script, this refers to the global object.

However, this changes when we use ES modules:

JAVASCRIPT
// Inside an ES module
console.log(this); // undefined
console.log(globalThis); // global object

Are all global variables attached to window?

No. This is an important distinction.

Consider:

JAVASCRIPT
var a = 10;
let b = 20;
const c = 30;

console.log(window.a); // 10
console.log(window.b); // undefined
console.log(window.c); // undefined

In a browser's classic script:

  • Global var declarations create properties on the global object.

  • Global let and const declarations do not create properties on the global object.

This distinction is important when working with the global execution context.

Quick note: this at the top level is not identical across all environments. For example, Node.js CommonJS modules have different top-level this behavior from browser classic scripts and ES modules.

3. How JavaScript Determines this: The Binding Rules

Now that we understand the global environment, let's explore how JavaScript decides the value of this when a function is invoked.

There are four major binding rules for regular functions:

  1. Default binding

  2. Implicit binding

  3. Explicit binding

  4. New binding

Arrow functions are different because they do not have their own this.

Rule 1: Default Binding

When a regular function is called without an owning object, it uses default binding.

JAVASCRIPT
function greet() {
  console.log(this);
}

greet();

What does this refer to?

It depends on strict mode and the execution environment:

  • In non-strict mode, this defaults to the global object.

  • In strict mode, this is undefined.

Example:

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

greet(); // undefined

Why does strict mode behave differently?

Because strict mode prevents JavaScript from automatically substituting the global object when a regular function is called without a receiver.

This helps avoid accidental modification of global variables.

Remember: A standalone regular function call uses default binding.

Rule 2: Implicit Binding

When a function is called as a method of an object, the object immediately before the dot becomes this.

JAVASCRIPT
const user = {
  name: "Alex",

  getDetails() {
    console.log(this.name);
  }
};

user.getDetails(); // Alex

Here, the function is invoked as:

JAVASCRIPT
user.getDetails();

The object immediately before the dot is user.

Therefore, this refers to user.

Let's make it slightly more interesting.

JAVASCRIPT
const user = {
  name: "Alex",

  childObj: {
    newName: "Consistcode",

    getDetails() {
      console.log(this.newName, "and", this.name);
    }
  }
};

user.childObj.getDetails();

Output:

JAVASCRIPT
Consistcode and undefined

Why?

Look carefully at the call:

JAVASCRIPT
user.childObj.getDetails();

The object immediately before .getDetails() is childObj.

So:

JAVASCRIPT
this === user.childObj;

JavaScript looks for:

JAVASCRIPT
this.newName; // "Consistcode"
this.name;    // undefined

It does not automatically search the parent object for name.

Important: this refers to the object used to invoke the method, not necessarily the outermost object.

Rule 3: Explicit Binding

What if we want to decide ourselves which object should be used as this?

JavaScript provides three methods:

  • call()

  • apply()

  • bind()

Let's understand them one by one.

A. call()

The call() method invokes a function immediately and lets us explicitly provide its this value.

JAVASCRIPT
function greet() {
  console.log("Hello " + this.name);
}

const user = {
  name: "Alex"
};

greet.call(user);

Output:

JAVASCRIPT
Hello Alex

We explicitly tell JavaScript to use user as this.

call() can also accept additional arguments:

JAVASCRIPT
function introduce(city, country) {
  console.log(
    `${this.name} lives in ${city}, ${country}`
  );
}

const user = {
  name: "Alex"
};

introduce.call(user, "Delhi", "India");

Output:

JAVASCRIPT
Alex lives in Delhi, India

B. apply()

apply() works like call(), but it accepts function arguments as an array (or array-like object).

JAVASCRIPT
introduce.apply(user, ["Delhi", "India"]);

Output:

JAVASCRIPT
Alex lives in Delhi, India

The difference is simple:

JAVASCRIPT
functionName.call(thisArg, arg1, arg2);
functionName.apply(thisArg, [arg1, arg2]);

C. bind()

Unlike call() and apply(), bind() does not invoke the function immediately.

Instead, it creates and returns a new function with a bound this value.

JAVASCRIPT
function greet() {
  console.log("Hello " + this.name);
}

const user = {
  name: "Alex"
};

const newGreet = greet.bind(user);

newGreet(); // Hello Alex

This is particularly useful when passing object methods as callbacks.

We will see why in the common pitfalls section.

Rule 4: New Binding

When we call a constructor function using the new keyword, JavaScript creates a new object and binds this to that object.

JAVASCRIPT
function User(name) {
  this.name = name;
}

const user1 = new User("Alex");

console.log(user1.name); // Alex

What happens behind the scenes?

When JavaScript executes:

JAVASCRIPT
const user1 = new User("Alex");

It performs these operations conceptually:

  1. Creates a new empty object.

  2. Links the new object's prototype to User.prototype.

  3. Executes the constructor with this referring to the new object.

  4. Returns the new object, unless the constructor explicitly returns another object.

So this line:

JAVASCRIPT
this.name = name;

is effectively adding a name property to the newly created instance.

The same principle applies to JavaScript classes:

JAVASCRIPT
class User {
  constructor(name) {
    this.name = name;
  }

  getName() {
    console.log(this.name);
  }
}

const user = new User("Alex");

user.getName(); // Alex

Important: Class constructors and class methods execute in strict mode. Calling a class method without its receiver does not automatically bind this to the instance.

4. The Precedence of this Binding Rules

Now we know the four binding rules. But what happens when more than one rule appears to apply?

JavaScript follows a precedence order.

For regular functions, the general order is:

  1. new binding

  2. Explicit binding (call, apply, bind)

  3. Implicit binding

  4. Default binding

Let's see an example.

JAVASCRIPT
function showName() {
  console.log(this.name);
}

const user1 = {
  name: "Alex"
};

const user2 = {
  name: "Jordan"
};

showName.call(user1); // Alex
showName.call(user2); // Jordan

Explicit binding takes control of this.

One important exception to remember: new can override a function's existing bind() binding.

JAVASCRIPT
function User(name) {
  this.name = name;
}

const user1 = {
  name: "Alex"
};

const BoundUser = User.bind(user1);

const user2 = new BoundUser("Jordan");

console.log(user2.name); // Jordan
console.log(user1.name); // Alex

Even though we bound User to user1, calling the bound function with new creates a new instance. The new instance receives this.

5. Arrow Functions and Lexical this

So far, we have discussed regular functions.

Arrow functions behave differently.

Arrow functions do not have their own this. They inherit this from their surrounding lexical scope.

This is called lexical this.

Consider:

JAVASCRIPT
const user = {
  name: "Alex",

  greet() {
    const inner = () => {
      console.log(this.name);
    };

    inner();
  }
};

user.greet(); // Alex

Let's understand what happened.

  1. greet() is called as user.greet().

  2. Therefore, this inside greet() refers to user.

  3. The arrow function does not create its own this.

  4. It uses the surrounding greet() function's this.

That is why the output is:

JAVASCRIPT
Alex

Arrow functions inside object methods

A common mistake is assuming that an arrow function automatically gets this from the object in which it is written.

It does not.

JAVASCRIPT
const user = {
  name: "Alex",

  greet: () => {
    console.log(this.name);
  }
};

user.greet();

The arrow function does not receive this from user.greet().

Instead, it inherits this from the surrounding scope where the arrow function was defined.

The exact output depends on that surrounding environment. For example, in a browser ES module, the top-level this is undefined, so accessing this.name throws a TypeError. In a browser classic script, it refers to the global object, where name may have a different value.

Remember: An arrow function inside an object is not automatically bound to that object.

Why are arrow functions useful?

They are especially useful when we want an inner callback to preserve the surrounding method's this.

JAVASCRIPT
const archer = {
  name: "Hawkeye",

  fireArrow() {
    setTimeout(() => {
      console.log(this.name + " hit the bullseye!");
    }, 50);
  }
};

archer.fireArrow();

Output:

JAVASCRIPT
Hawkeye hit the bullseye!

The arrow callback inherits this from fireArrow(), where this refers to archer.

This is one of the most common real-world uses of lexical this.

6. Common Pitfalls: Losing this

One of the most confusing situations for developers is when a method works correctly on an object but stops working after being passed as a callback.

Let's understand why.

A. Extracting a method from an object

JAVASCRIPT
const warrior = {
  name: "Thor",

  shout() {
    console.log("I am " + this.name);
  }
};

warrior.shout(); // I am Thor

This works because of implicit binding.

But what happens here?

JAVASCRIPT
const detachedShout = warrior.shout;

detachedShout();

The function is no longer invoked as a method of warrior.

It is now a standalone function call.

Therefore, it uses default binding.

In strict mode, this is undefined, so accessing this.name throws a TypeError. In non-strict mode, this is the global object, and the output depends on whether that object has a name property.

B. Fixing it with bind()

JAVASCRIPT
const boundShout = warrior.shout.bind(warrior);

boundShout(); // I am Thor

bind() creates a new function that keeps this bound to warrior.

C. Losing this in event listeners

Consider this example:

JAVASCRIPT
const user = {
  name: "Alex",

  handleClick() {
    console.log(this.name);
  }
};

button.addEventListener("click", user.handleClick);

Why might this not print "Alex"?

Because when a regular function is used as a DOM event listener, the browser invokes it with this referring to the element on which the listener was registered.

So inside handleClick(), this refers to the button, not the user object.

We can fix this in two ways.

Solution 1: Use an arrow wrapper

JAVASCRIPT
button.addEventListener("click", (event) => {
  user.handleClick(event);
});

The arrow function calls user.handleClick() as an object method, preserving the intended receiver.

Solution 2: Use bind()

JAVASCRIPT
button.addEventListener(
  "click",
  user.handleClick.bind(user)
);

Now the listener receives a function whose this is bound to user.

7. Interview Questions and Output-Based Examples

Let's test our understanding with some common interview questions.

Question 1: What is the output?

JAVASCRIPT
let a = 5;

console.log(this.a);

Answer: This depends on the execution environment.

In a browser classic script:

JAVASCRIPT
undefined

Why?

Because a top-level let declaration does not create a property on window.

JAVASCRIPT
window.a; // undefined

The top-level this in a browser classic script refers to window, but a is not a property of window.

Question 2: What is the output?

JAVASCRIPT
let user = {
  name: "Alex",
  age: 24,

  getDetails() {
    console.log(this.name);
  }
};

user.getDetails();

Output:

JAVASCRIPT
Alex

Explanation: The function is invoked as user.getDetails(). Therefore, this refers to user.

Question 3: What is the output?

JAVASCRIPT
let user = {
  name: "Alex",
  age: 24,

  childObj: {
    newName: "Consistcode",

    getDetails() {
      console.log(this.newName, "and", this.name);
    }
  }
};

user.childObj.getDetails();

Output:

JAVASCRIPT
Consistcode and undefined

Explanation: childObj is the object immediately before .getDetails(). Therefore, this refers to childObj, which has newName but does not have name.

Question 4: What is the output?

JAVASCRIPT
class User {
  constructor(n) {
    this.name = n;
  }

  getName() {
    console.log(this.name);
  }
}

const user = new User("Alex");

user.getName();

Output:

JAVASCRIPT
Alex

Explanation: The new keyword creates a new instance and binds this to that instance during construction. Later, user.getName() invokes the method with user as its receiver.

Question 5: Find the mistake.

JAVASCRIPT
const user = {
  firstName: "Alex",

  getName() {
    const firstName = "Alex";
    return this.firstName;
  }
};

console.log(object.getMessage());

Answer: There are two issues:

  1. The object is named user, not object.

  2. The method is named getName(), not getMessage().

Correct code:

JAVASCRIPT
console.log(user.getName());

Output:

JAVASCRIPT
Alex

Notice that getName() returns this.firstName, which refers to the object's property. The local variable firstName is not used.

Question 6: What happens when we access user.ref.name?

JAVASCRIPT
function makeUser() {
  return {
    name: "John",
    ref: this
  };
}

let user = makeUser();

console.log(user.ref.name);

Answer: It depends on how makeUser() is called and the environment.

makeUser() is called as a standalone function.

  • In non-strict browser script code, this refers to the global object. user.ref.name therefore reads the global object's name property, not "John".

  • In strict mode or an ES module, this is undefined, so accessing user.ref.name throws a TypeError.

The important lesson is that this inside makeUser() does not automatically refer to the object being returned.

If we want ref to point to the returned object itself, we need to create the object first:

JAVASCRIPT
function makeUser() {
  const user = {
    name: "John"
  };

  user.ref = user;

  return user;
}

const user = makeUser();

console.log(user.ref.name); // John

Question 7: What gets logged?

JAVASCRIPT
const user = {
  name: "Alex Morgan",

  logMessage() {
    console.log(this.name);
  }
};

setTimeout(user.logMessage, 1000);

Answer: The method is passed as a callback without its original object receiver.

Therefore, this does not refer to user.

The exact value depends on the timer environment and function execution context. In a browser, timer callbacks typically receive the global object as this; in Node.js, timer callbacks have their own timer-related receiver.

To preserve the intended object, use:

JAVASCRIPT
setTimeout(user.logMessage.bind(user), 1000);

Or:

JAVASCRIPT
setTimeout(() => {
  user.logMessage();
}, 1000);

Both preserve the intended user receiver.

Question 8: What is the output?

JAVASCRIPT
const user = {
  name: "Alex",

  greet() {
    return `Hello, ${this.name}!`;
  },

  farewell: () => {
    return `Goodbye, ${this.name}!`;
  }
};

console.log(user.greet());
console.log(user.farewell());

Answer:

The first output is:

JAVASCRIPT
Hello, Alex!

The regular method gets this from the method invocation, so this refers to user.

The second output is environment-dependent.

The arrow function does not have its own this. It inherits this from the surrounding scope where the object was created.

It does not get this from user.farewell().

This is why using arrow functions as object methods can produce unexpected results.

Question 9: Implement the calculator.

We want to execute:

JAVASCRIPT
const result = calculator
  .add(10)
  .multiply(5)
  .subtract(30)
  .add(10);

console.log(result.total);

Expected output:

JAVASCRIPT
30

How can we implement this?

JAVASCRIPT
const calculator = {
  total: 0,

  add(a) {
    this.total += a;
    return this;
  },

  subtract(a) {
    this.total -= a;
    return this;
  },

  multiply(a) {
    this.total *= a;
    return this;
  }
};

const result = calculator
  .add(10)
  .multiply(5)
  .subtract(30)
  .add(10);

console.log(result.total);

Output:

JAVASCRIPT
30

Let's understand the calculation:

Operation

Calculation

Total

Initial value

—

0

add(10)

0 + 10

10

multiply(5)

10 × 5

50

subtract(30)

50 - 30

20

add(10)

20 + 10

30

The important part is:

JAVASCRIPT
return this;

Each method returns the same calculator object, allowing us to call the next method on it.

This technique is called method chaining.

Question 10: What is the output?

JAVASCRIPT
var length = 4;

function callback() {
  console.log(this.length);
}

const object = {
  length: 5,

  method(callback) {
    callback();
  }
};

object.method(callback, 1, 2);

Answer: The important thing is that callback() is invoked as a standalone function inside method().

It is not invoked as:

JAVASCRIPT
object.callback();

Therefore, this inside callback does not refer to object.

The extra arguments 1 and 2 are also ignored because method only declares one parameter.

The exact value of this.length depends on the environment. In a browser classic script, window.length is a special property representing the number of frames in the window, so it is not safe to assume that the answer is simply 4. In Node.js, the global and module environments differ as well.

The key interview lesson: passing a function as an argument does not automatically preserve the object from which it came.

8. Quick Revision: The this Cheat Sheet

Situation

Value of this

Standalone regular function, non-strict mode

Global object

Standalone regular function, strict mode

undefined

user.greet()

user

greet.call(user)

user

greet.apply(user, args)

user

greet.bind(user)

Bound function uses user

new User()

Newly created instance

Arrow function

Inherits lexical this

Five Things to Remember

  1. Regular functions: this is determined by how the function is called.

  2. Implicit binding: In obj.method(), this refers to obj.

  3. Explicit binding: call(), apply(), and bind() let us control this.

  4. Constructor binding: new binds this to the newly created instance.

  5. Arrow functions: They do not have their own this; they inherit it from the surrounding lexical scope.

What's Next?

We now understand how JavaScript determines the value of this in different situations.

But there is another important concept behind JavaScript objects that explains how objects share properties and methods.

In the next chapter, we will explore Prototypes and Prototypal Inheritance—how JavaScript objects connect to other objects and how property lookup works through the prototype chain.

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.