Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 156 ยท Functions

The this Keyword

Learn how JavaScript sets this in methods, plain function calls, arrow functions, classes and event handlers, and how to fix the classic lost this bug.

this is a special keyword that a function can use to refer to "the object I'm working with right now". In a method like user.greet(), this is user, so the same method code can work for any user object. That sounds simple, and in methods it is.

The tricky part is that, for regular functions, this is not decided where the function is written. It is decided each time the function is called, by how it is called. Call the very same function in a different way and this changes โ€” sometimes to undefined, sometimes to the global window object. This lesson walks through every way a function can be called, shows what this becomes in each case, and fixes the famous "lost this" bug.

this in methods

When you call a function as a property of an object โ€” object.method() โ€” this inside it is the object to the left of the dot:

JS this is the object before the dot

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There is only one describe function, shared by both objects. Each call gets a different this because each call has a different object before the dot. This is what makes methods reusable.

this in a plain function call

What if a regular function is called on its own, with nothing before the dot? The answer depends on whether the code runs in strict mode:

  • In sloppy mode (the default for classic scripts), this is the global object โ€” window in browsers.
  • In strict mode, this is undefined.

Strict mode is switched on by a "use strict"; line at the top of a script or function, and it is automatic inside modules and class bodies.

The console editors on this site run your code as a classic script, exactly like a plain <script> tag, so the top level is sloppy:

JS Classic script: sloppy mode

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same code behaves differently as a module. This editor runs it with type="module", which makes everything strict:

JS Module: strict mode everywhere

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The undefined in strict mode is a good thing. With sloppy mode, a function that accidentally runs without its object quietly reads and writes properties on window. With strict mode it fails immediately with a clear error. (For completeness: in a Node.js CommonJS file, top-level this is module.exports, an empty object to begin with. When you need the global object in any environment, use globalThis.)

Losing this

The most common this bug: you take a method off its object and call it later. The function no longer has anything before the dot, so it becomes a plain call.

JS A method detached from its object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the sloppy script, detached() reads window.label, which doesn't exist, so you get "I am undefined" โ€” a silent bug. The class method is strict, so this is undefined and reading this.label throws a TypeError. (Chromium says "Cannot read properties of undefined (reading 'label')"; other browsers word it differently.)

Detaching happens more often than you'd think, because passing a method as a callback detaches it:

JavaScript
setTimeout(player.describe, 100);       // describe runs without player
[1, 2].forEach(bot.describe);           // same problem
button.addEventListener("click", bot.describe); // this becomes the button!

Three ways to keep this

  1. Wrap the call in an arrow function, so it is still a method call: setTimeout(() => player.describe(), 100).
  2. Bind the method to its object: setTimeout(player.describe.bind(player), 100). The next lesson, call, apply and bind, covers this in detail.
  3. In a class, use an arrow function as a class field, so each instance gets a function that always uses that instance: describe = () => `I am ${this.label}`;

Arrow functions use the outer this

Arrow functions don't have their own this. They look it up in the surrounding code, like any other variable, and it never changes no matter how the arrow is called. That makes them perfect for callbacks inside methods:

JS Regular vs arrow callbacks inside a method

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In listRegular, the inner function is called by map() as a plain function, so its this is window, which has no teamName โ€” you get "Ana of undefined". In strict code, this would be undefined and the line would throw instead. The arrow version uses listArrow's own this, which is team.

The flip side, as you saw in the arrow functions lesson, is that an arrow used as a method doesn't get the object either. Arrows inside methods: yes. Arrows as methods: no.

this with new and classes

When a function is called with new โ€” or a class is instantiated โ€” JavaScript creates a fresh object and runs the constructor with this set to that new object:

JavaScript
class Lamp {
  constructor(color) {
    this.color = color; // this is the new Lamp
    this.on = false;
  }
  toggle() {
    this.on = !this.on;
    return this;        // returning this allows chaining
  }
}

const lamp = new Lamp("amber");
lamp.toggle().toggle().toggle();
lamp.on; // true

Inside class methods, this follows the method-call rules: it is the instance before the dot. And because class bodies are always strict, a detached class method gets undefined, never window.

this in event handlers

When you register a regular function with addEventListener(), the browser calls it with this set to the element the listener is attached to โ€” the same element as event.currentTarget. An arrow function ignores that and keeps the outer this:

this in event listeners

Using event.currentTarget works in both styles and makes the code clearer, so many developers prefer it to this in handlers. See the Events lesson for more.

The rules in order

To find this for a call, check these rules from top to bottom; the first one that applies wins:

How the function is called this is
It is an arrow function The this of the surrounding code, always
new Fn() or new Class() The newly created object
fn.call(obj), fn.apply(obj) or a function made by fn.bind(obj) obj
obj.fn() obj
fn() on its own undefined in strict code; globalThis (window) in sloppy code

Callers like addEventListener() and array methods with a thisArg parameter apply rule three for you behind the scenes.

Write strict code. Use modules or classes (both are strict automatically), and a lost this will throw an error right where the bug is, instead of silently reading from window.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is this inside cart.total() when called exactly like that?

    For a method call, this is the object before the dot.
  2. 2. In a classic (non-module) script without "use strict", what does function f() { return this; } f() === window evaluate to?

    In sloppy mode a plain call gets the global object as this. In strict mode or a module it would be undefined.
  3. 3. What is this at the top level of a JavaScript module?

    Modules are strict and their top-level this is undefined. In a classic script it would be window.
  4. 4. const fn = robot.speak; fn(); throws a TypeError, but robot.speak() works. Why?

    this is decided by how the function is called. Without an object before the dot, a strict function gets undefined.
  5. 5. Inside a method, why does an arrow callback passed to map() see the method's this?

    Arrows resolve this lexically, so inside a method they use the method's this.

Summary

  • For regular functions, this is set by how the function is called, not where it is written.
  • obj.method() gives this = obj; new gives the new object; call/apply/bind give whatever you pass.
  • A plain call gets undefined in strict code (modules, classes, "use strict") and window in sloppy classic scripts; top-level this follows the same split.
  • Passing a method as a callback detaches it; fix it with an arrow wrapper, bind() or an arrow class field.
  • Arrow functions always use the surrounding this: great inside methods, wrong as methods.
  • Regular event listeners get the element as this; event.currentTarget is the clearer alternative.

Next: call, apply and bind โ€” choosing this yourself.