Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript this Keyword

The this keyword refers to the object a function is called on.

Its value changes based on the call site.

Why We Need It

Misunderstanding this is a common source of bugs.

Knowing how this works makes methods and callbacks safer.

Syntax

obj.method()
fn.call(obj)
fn.bind(obj)

Basic Example

1. Method call

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

console.log(user.greet());

this refers to user.

Real World Example

2. Detached function

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

const fn = user.greet;
console.log(fn());

this is undefined in strict mode when detached.

Multiple Use Cases

Call Site Matters

this depends on how a function is called, not where it is defined.

In methods, this refers to the object before the dot.

Arrow Functions

Arrow functions do not have their own this.

They capture this from the surrounding scope.

Common Pitfalls

Losing this happens when you pass a method as a callback.

Use bind, call, or arrow wrappers to keep context.

More Examples

3. Bind this

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

const bound = user.greet.bind(user);
console.log(bound());

bind fixes the context.

4. Arrow in callback

const team = {
  name: "Blue",
  members: ["A", "B"],
  list() {
    return this.members.map((m) => this.name + "-" + m);
  }
};

console.log(team.list());

Arrow function uses outer this.

Comparison

Without

const fn = user.greet;
fn(); // this is undefined

With

const fn = user.greet.bind(user);
fn(); // this is user

Common Mistakes and Fixes

Using this in arrow methods

Arrows do not bind this; use method syntax instead.

Passing methods directly

Bind the method or wrap it in a function.

Assuming this is global

In strict mode, this is undefined in standalone calls.

Interview Questions

What determines this?

The way a function is called.

Why use bind?

To lock this to a specific object.

Does arrow have this?

No, arrows use lexical this.

Practice Problem

Practice: Fix a method call so this refers to the object.

const user = { name: "Ava", greet() { return "Hi " + this.name; } };
const fn = user.greet;
// TODO: call with correct this

One Possible Solution

const user = { name: "Ava", greet() { return "Hi " + this.name; } };
const fn = user.greet.bind(user);
console.log(fn());

Frequently Asked Questions

What does this refer to?

It depends on how the function is called.

Do arrow functions have this?

No, they capture this from their scope.

How do I keep this in callbacks?

Use bind or arrow functions.

Try It Yourself

Try detaching methods and see how this changes.