What is the 'this' keyword?

this is a value set when a function is called (not where it is defined), and it refers to the object the function is acting on; arrow functions are the exception, taking this from the surrounding scope.

The rules, in priority order

  1. new binding: new Fn() sets this to the newly created object.
  2. Explicit binding: fn.call(obj), fn.apply(obj) or fn.bind(obj) set this to obj.
  3. Implicit binding: obj.method() sets this to obj (whatever is left of the dot at call time).
  4. Default binding: a plain call fn() gives undefined in strict mode (and in modules and classes), or the global object in sloppy mode.

Arrow functions ignore all of these and use this from where they were written.

Losing this

The most common bug: passing a method as a callback (setTimeout(obj.method) or onClick={this.handle}) detaches it from the object, so the call becomes a plain call and this is undefined. Fixes: bind, an arrow wrapper, or class field arrow methods.

Other contexts

  • In a class body and ES modules, code runs in strict mode.
  • In DOM event handlers written as normal functions, this is the element the listener is attached to (event.currentTarget).
  • At the top level of a module this is undefined; in a classic browser script it is window.

Code example

js
1"use strict";
2
3const user = {
4 name: "Ada",
5 greet() {
6 return `Hi, I am ${this?.name}`;
7 },
8};
9
10console.log(user.greet()); // implicit: Hi, I am Ada
11
12const detached = user.greet;
13console.log(detached()); // default (strict): Hi, I am undefined
14
15console.log(detached.call({ name: "Linus" })); // explicit: Hi, I am Linus
16const bound = user.greet.bind(user);
17console.log(bound()); // bound: Hi, I am Ada
18
19function Person(name) {
20 this.name = name; // `new` binding: this = new object
21}
22console.log(new Person("Grace").name); // Grace
23
24class Clock {
25 ticks = 0;
26 tick = () => ++this.ticks; // arrow class field: always this instance
27}
28const clock = new Clock();
29const fn = clock.tick; // safe to pass around
30fn();
31fn();
32console.log(clock.ticks); // 2

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app