The This Keyword

Updated · 10 min read

this is a special keyword that refers to the object a function is working on. Unlike most languages, where this always means the current instance, JavaScript decides this each time a function is called, based on how it was called. The same function can have different this values in different calls. Four rules (default, implicit, explicit and new binding) plus one exception (arrow functions) explain every case, and knowing them ends the most common source of JavaScript confusion.

In One Minute

  • Implicit binding: obj.method() sets this to obj (the object before the dot).
  • Default binding: a plain call fn() sets this to undefined in strict mode (modules, classes), or the global object in sloppy scripts.
  • Explicit binding: fn.call(obj), fn.apply(obj) and fn.bind(obj) set this to obj.
  • new binding: new Fn() sets this to the newly created object.
  • Arrow functions have no this of their own: they use the this of the surrounding code.

The Four Rules

RuleHow the function is calledthis is
new bindingnew Account()The new object
Explicit bindingfn.call(obj), fn.apply(obj), fn.bind(obj)()obj
Implicit bindingobj.fn()obj
Default bindingfn()undefined (strict) or globalThis (sloppy)

When several could apply, the order of precedence is the order of the table: new beats explicit, which beats implicit, which beats default.

Implicit Binding: The Object Before the Dot

implicit.js▶ Try it
function describe() {
  return `${this.name} owes $${this.balance}`;
}
 
const navika = { name: "Navika", balance: 120, describe };
const advitha = { name: "Advitha", balance: 45, describe };
 
console.log(navika.describe());
console.log(advitha.describe());
 
const school = { student: navika };
console.log(school.student.describe());
Output
Navika owes $120
Advitha owes $45
Navika owes $120

Explanation: one function, three calls. In each, this is the object immediately before the final dot: navika, advitha, and in school.student.describe(), school.student, which is navika. Where the function was defined doesn't matter at all.

Default Binding: A Plain Call

When a function is called without an object (no dot, no call, no new), there is nothing to bind this to:

default.js▶ Try it
function sloppyThis() {
  return this === globalThis;
}
 
function strictThis() {
  "use strict";
  return this;
}
 
console.log(sloppyThis());
console.log(strictThis());
Output
true
undefined

In strict mode (which includes all ES modules and class bodies), this is undefined. In older non-strict scripts, it falls back to the global object, which is how code accidentally created global variables. Modern code should treat this in a plain call as undefined.

The Lost this Bug

Implicit binding happens only at the moment of the call obj.method(). Taking the method off the object, by storing it in a variable or passing it as a callback, loses the binding:

lost.js▶ Try it
"use strict";
const account = {
  owner: "Srihitha",
  describe() {
    return `Owner: ${this.owner}`;
  },
};
 
const detached = account.describe;
try {
  detached();
} catch (err) {
  console.log(err.name + ": " + err.message);
}
 
function runLater(callback) {
  return callback();
}
try {
  runLater(account.describe);
} catch (err) {
  console.log("as a callback:", err.name);
}
Output
TypeError: Cannot read properties of undefined (reading 'owner')
as a callback: TypeError

account.describe (without parentheses) is just the function. When it is called later as callback(), it's a plain call, so this is undefined. This happens with timers, event listeners, promise callbacks, array methods and React event props.

Three Fixes

fixes.js▶ Try it
const account = {
  owner: "Srihitha",
  describe() {
    return `Owner: ${this.owner}`;
  },
};
const runLater = (callback) => callback();
 
console.log(runLater(() => account.describe()));
console.log(runLater(account.describe.bind(account)));
 
class Account {
  owner = "Advitha";
  describe = () => `Owner: ${this.owner}`;
}
console.log(runLater(new Account().describe));
Output
Owner: Srihitha
Owner: Srihitha
Owner: Advitha
FixHowTrade-off
Wrap in an arrow() => obj.method()Clear; a new function each time
bindobj.method.bind(obj)Permanent this; keep the bound function if you need to remove a listener
Arrow-function class fieldmethod = () => { ... }Bound per instance automatically; uses memory per instance, not shared on the prototype

Explicit Binding: call, apply and bind

These three methods, available on every function, set this explicitly. They have their own lesson next; in short:

explicit.js▶ Try it
function describe(prefix, suffix) {
  return `${prefix}${this.name} owes $${this.balance}${suffix}`;
}
const student = { name: "Advitha", balance: 45 };
 
console.log(describe.call(student, "Note: ", "."));
console.log(describe.apply(student, ["Note: ", "!"]));
 
const bound = describe.bind(student, "Reminder: ");
console.log(bound("?"));
Output
Note: Advitha owes $45.
Note: Advitha owes $45!
Reminder: Advitha owes $45?

call and apply call the function immediately (arguments listed, or as an array); bind returns a new function with this (and optionally some arguments) fixed.

new Binding

When a function is called with new, JavaScript creates a new object and sets this to it:

new.js▶ Try it
function Payment(name, amount) {
  this.name = name;
  this.amount = amount;
}
 
const p = new Payment("Navika", 120);
console.log(p.name, p.amount, p instanceof Payment);
 
const bound = Payment.bind({ ignored: true });
const q = new bound("Srihitha", 85);
console.log(q.name, "ignored" in q);
Output
Navika 120 true
Srihitha false

The second example shows precedence: new beats bind. Even a bound function gets the brand new object as this when called with new.

Arrow Functions: No Own this

Arrow functions don't have their own this. Inside an arrow, this is whatever it was in the surrounding scope at the place the arrow was written (lexical this). None of the four rules applies to arrows, and call, apply and bind can't change it:

arrows.js▶ Try it
const tracker = {
  owner: "Navika",
  amounts: [120, 60],
  labels() {
    return this.amounts.map((a) => `${this.owner}: ${a}`);
  },
  broken() {
    return this.amounts.map(function (a) {
      return `${this?.owner}: ${a}`;
    });
  },
};
 
console.log(tracker.labels());
console.log(tracker.broken());
 
const arrow = () => this === globalThis;
console.log(arrow.call({ x: 1 }));
Output
['Navika: 120', 'Navika: 60']
['undefined: 120', 'undefined: 60']
true

Explanation: inside labels, the arrow callback uses the method's this, which is tracker. In broken, the regular function callback is called by map as a plain function, so it gets its own, default this. The last line shows that call can't override an arrow's this: the arrow keeps the this of the code around it (here the top level of a non-module script, where this is the global object), even though call passed a different object.

Regular functionArrow function
this decided byHow it's calledWhere it's written
call/apply/bind change thisYesNo
Use as an object methodYesNo (no access to the object)
Use as a callback inside a methodLoses thisKeeps the method's this

this in Classes and Event Handlers

Classes are always strict, and their methods follow the same rules: instance.method() binds the instance; a detached method gets undefined.

Event listeners added with addEventListener and a regular function get this set to the element the listener is attached to (the same as event.currentTarget). With an arrow function, they don't:

event-this.html
<button id="pay">Pay</button>
<script>
  const button = document.querySelector("#pay");
  button.addEventListener("click", function (event) {
    console.log("regular:", this.id, this === event.currentTarget);
  });
  button.addEventListener("click", (event) => {
    console.log("arrow:", this === undefined || this === window, event.currentTarget.id);
  });
</script>
Output
regular: pay true
arrow: true pay

In Practice

The Fee Tracker's Reminder class schedules a reminder with a timer. Passing the method directly would lose this; an arrow wrapper keeps it:

reminder.js▶ Try it
class Reminder {
  constructor(student) {
    this.student = student;
    this.sent = 0;
  }
  send() {
    this.sent++;
    console.log(`Reminder ${this.sent} sent to ${this.student}`);
  }
  schedule(ms) {
    setTimeout(() => this.send(), ms);
  }
}
 
const r = new Reminder("Advitha");
r.schedule(10);
r.schedule(20);
Output
Reminder 1 sent to Advitha
Reminder 2 sent to Advitha

Inside schedule, this is the instance (r.schedule(...)), and the arrow passed to setTimeout keeps it, so this.send() works when the timer fires.

Common Mistakes

Passing obj.method as a callback. this is lost. Wrap it: () => obj.method(), or bind.

Using an arrow function as an object method. It can't see the object. Use method shorthand.

Expecting bind to work on an arrow. It doesn't change an arrow's this.

Assuming this means the same thing everywhere in a file. It depends on each call.

Under the Hood

When a function is called, the engine computes a this value as part of creating the call's execution context. For a property reference call like obj.method(), the specification's call evaluation records the base object (obj) of the reference and passes it as this. For a plain identifier call, there is no base object, so undefined is passed; non-strict functions then replace undefined (and null) with the global object, and wrap primitives in objects ("text".method() in sloppy mode gets a String object). call and apply pass their first argument directly as the this value. bind creates a bound function exotic object that remembers a target function, a bound this and bound arguments, and always calls the target with them, except under new, which ignores the bound this. Arrow functions are created with a flag that makes them lexical-this functions: they skip the this binding step entirely, so this inside them resolves through the scope chain like an ordinary variable, finding the nearest enclosing non-arrow function's this.

Interview Corner

How is this determined in JavaScript?

At call time, by how the function is invoked: with new, this is the new object; with call, apply or a bound function, it's the provided value; as obj.method(), it's obj; as a plain call, it's undefined in strict mode or the global object otherwise. Arrow functions don't bind this; they use the enclosing scope's this. Precedence: new, explicit, implicit, default.

Why does a method lose this when passed as a callback?

Implicit binding comes from the obj. in the call expression. Passing obj.method passes only the function value; the receiver later calls it as a plain function, so default binding applies. Fix with an arrow wrapper, bind, or an arrow-function class field.

What does this print?

Show solution
puzzle.js▶ Try it
"use strict";
const obj = {
  value: 42,
  regular() { return this?.value; },
  arrow: () => typeof this,
  nested() { return [1].map(() => this.value)[0]; },
};
const { regular } = obj;
console.log(obj.regular(), regular(), obj.arrow(), obj.nested());
Output
42 undefined undefined 42

obj.regular() binds obj. The destructured regular() is a plain call in strict mode. The arrow at object-literal level uses the surrounding this (here undefined). nested's arrow uses nested's this, which is obj.

Practice

Challenge: Fix the code below so that clicking (simulated by calling handler()) logs Saved by Navika, without changing the save method.

practice.js
const user = {
  name: "Navika",
  save() { return `Saved by ${this.name}`; },
};
const handler = user.save;
console.log(handler());
Show solution
practice-solution.js▶ Try it
"use strict";
const user = {
  name: "Navika",
  save() { return `Saved by ${this.name}`; },
};
const handler = user.save.bind(user);
console.log(handler());
Output
Saved by Navika

Quick check: this

3 questions
1In school.student.describe(), what is this inside describe?
2What is this inside a plain function call fn() in strict mode?
3Can bind change the this of an arrow function?

Key Takeaways

Callthis
new Fn()The new object
fn.call(obj)obj
obj.fn()obj
fn() (strict)undefined
Arrow functionSurrounding scope's this

Was this tutorial helpful?

Lesson 93 of 139