TExcelTAD
Home › JavaScript › JS this Keyword

JavaScript this Keyword

this is a special variable that every regular function gets automatically. It refers to the object the function is working on — but which object that is depends on how the function is called, not where it's defined. That makes this one of the most confusing parts of JavaScript, so let's go through the rules one at a time.

The rules at a glance

How the function is called this is
As a method: obj.method() obj (the object before the dot)
As a plain function: fn() undefined in strict mode (global object in sloppy mode)
With new: new Fn() the newly created object
With call/apply/bind whatever object you pass
Arrow function inherited from the surrounding code
Event handler el.addEventListener(…, function) the element
At the top level of a module undefined

Method calls

When a function is called as object.method(), this is the object to the left of the dot:

js · try it yourself
const account = {
  owner: "Rosa",
  balance: 120,
  deposit(amount) {
    this.balance += amount;
    return `${this.owner} now has ${this.balance}`;
  },
};

console.log(account.deposit(30));

const other = { owner: "Tim", balance: 5, deposit: account.deposit };
console.log(other.deposit(10));   // same function, different `this`
Rosa now has 150
Tim now has 15

The same function gave different results because this was decided at call time.

Losing this

If you take a method out of its object and call it on its own, the "object before the dot" is gone. In strict mode (modules, classes) this becomes undefined:

js · try it yourself
const counter = {
  count: 0,
  increment() {
    this.count++;
    return this.count;
  },
};

const inc = counter.increment;   // just the function, detached
try {
  inc();
} catch (err) {
  console.log(err.message);
}
Cannot read properties of undefined (reading 'count')

This happens a lot when passing methods as callbacks, e.g. setTimeout(counter.increment, 100) or button.addEventListener("click", obj.handle).

Fixing it: bind, call and apply

These function methods set this explicitly:

  • fn.call(obj, a, b) — call now with this = obj and arguments listed.
  • fn.apply(obj, [a, b]) — same, but arguments as an array.
  • fn.bind(obj) — returns a new function permanently bound to obj.
js · try it yourself
function introduce(greeting, punctuation) {
  return `${greeting}, I'm ${this.name}${punctuation}`;
}

const ada = { name: "Ada" };
const alan = { name: "Alan" };

console.log(introduce.call(ada, "Hello", "!"));
console.log(introduce.apply(alan, ["Hi", "."]));

const counter = {
  count: 0,
  increment() {
    return ++this.count;
  },
};
const boundInc = counter.increment.bind(counter);
boundInc();
console.log(boundInc());
Hello, I'm Ada!
Hi, I'm Alan.
2

Arrow functions don't have their own this

An arrow function uses the this of the code around it — wherever it was written. That's exactly what you want for callbacks inside methods:

js · try it yourself
const team = {
  name: "Rockets",
  members: ["Lia", "Sam"],
  listWithArrow() {
    return this.members.map((m) => `${m} plays for ${this.name}`);
  },
  listWithFunction() {
    return this.members.map(function (m) {
      return `${m} plays for ${this?.name}`;   // `this` is undefined here
    });
  },
};

console.log(team.listWithArrow());
console.log(team.listWithFunction());
[ 'Lia plays for Rockets', 'Sam plays for Rockets' ]
[ 'Lia plays for undefined', 'Sam plays for undefined' ]

But the flip side: don't use an arrow function as an object method — it won't get the object as this.

this in classes and constructors

With new, this is the brand-new object being built. In class methods it's the instance the method was called on:

js · try it yourself
class Timer {
  constructor(label) {
    this.label = label;
    this.ticks = 0;
  }
  tick() {
    this.ticks++;
    return `${this.label}: ${this.ticks}`;
  }
}

const t = new Timer("egg");
t.tick();
console.log(t.tick());
console.log(this);   // top level of a module
egg: 2
undefined

this in event handlers

In a DOM event listener written with a regular function, this is the element the listener is attached to (the same as event.currentTarget). With an arrow function it's the outer this:

html · try it yourself
<button id="btn">Click me</button>
<script>
  document.getElementById("btn").addEventListener("click", function () {
    this.textContent = "Clicked (this = " + this.tagName + ")";
  });
</script>

Tip: If this confuses you in a callback, check how the function is called. The fix is almost always an arrow function, or .bind(obj).

Test yourself

In user.greet(), what is this inside greet (a regular function)?

  1. The global object
  2. user
  3. greet
  4. undefined

What does fn.bind(obj) return?

  1. The result of calling fn
  2. A new function with this fixed to obj
  3. obj
  4. undefined

Where does an arrow function get its this from?

  1. The object before the dot
  2. The caller
  3. The surrounding (enclosing) scope
  4. It is always undefined