Tutorials / Modern JavaScript: Async, Modules and the Browser / Understanding this in JavaScript

Understanding this in JavaScript

14 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

Why this confuses people

In most languages, this points to the object a method belongs to. In JavaScript, this depends on how a function is called, not where it is written. The same function can have different this values on different calls. Once you know the four rules, it stops being a mystery.

Rule 1: method call

When you call a function as object.method(), this is the object before the dot.

const user = {
  name: "Sara",
  greet() {
    return `Hi, I am ${this.name}`;
  },
};

console.log(user.greet()); // Hi, I am Sara

Rule 2: plain function call

When you call a function by itself, there is no object. In strict mode (which modules and classes use), this is undefined. In old sloppy-mode scripts it falls back to the global object.

function show() {
  return this;
}
console.log(show()); // undefined in strict mode, the global object otherwise

The classic problem: losing this

Take a method out of its object and this is gone:

const greet = user.greet;     // just a function now
// greet();                   // TypeError or "Hi, I am undefined"

The same thing happens when you pass a method as a callback, since the receiving code calls it as a plain function:

setTimeout(user.greet, 100);        // this is lost
button.addEventListener("click", user.greet);  // here this is the button!

Classes behave the same way. If you pass account.describe to something, you have passed only the function, not the account.

Fix 1: wrap it in an arrow function

setTimeout(() => user.greet(), 100);

The call is user.greet(), a method call, so this is right. This is the fix I use most.

Fix 2: bind

bind returns a new function with this fixed to the value you give.

const boundGreet = user.greet.bind(user);
console.log(boundGreet()); // Hi, I am Sara
setTimeout(boundGreet, 100);

Rule 3: explicit this with call and apply

call and apply run a function immediately with a chosen this. They differ only in how arguments are passed.

function introduce(greeting, punctuation) {
  return `${greeting}, I am ${this.name}${punctuation}`;
}

const ali = { name: "Ali" };

console.log(introduce.call(ali, "Hello", "!"));     // arguments one by one
console.log(introduce.apply(ali, ["Hello", "!"]));  // arguments in an array

You will not need these often in new code, but they appear in library code and older tutorials.

Rule 4: new

When you use new, JavaScript creates a fresh empty object and this points to it inside the constructor. That is how this.owner = owner in a class constructor works.

Arrow functions are different

An arrow function has no this of its own. It takes this from the surrounding code where it was written, and nothing about how you call it can change that.

const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds++;           // this is the timer, from start()
      console.log(this.seconds);
    }, 1000);
  },
};
// timer.start();

Here the arrow function inside start uses the this of start, which is timer. If we had used a normal function () { ... } for the callback, this would be wrong inside it.

The flip side is that arrow functions are the wrong choice for object methods and event handlers where you want this to be the element:

const counter = {
  count: 0,
  // wrong: this is not counter here
  badIncrement: () => { this.count++; },
  // right
  increment() { this.count++; },
};

A table of rules

How the function is calledValue of this
obj.method()obj
fn()undefined (strict) or global
fn.call(x), fn.apply(x), fn.bind(x)()x
new Fn()The new object
Arrow functionthis of the surrounding code
DOM event handler (normal function)The element

Class methods as event handlers

A common pattern in classes is to bind or use an arrow function field:

class Menu {
  constructor(button) {
    this.open = false;
    button.addEventListener("click", () => this.toggle());
  }
  toggle() {
    this.open = !this.open;
    console.log(this.open);
  }
}

The arrow function calls this.toggle() as a proper method call, so everything works.

Common mistakes

  • **Passing obj.method as a callback.** Wrap it in an arrow function or use bind.
  • Using an arrow function for an object method. this will not point to the object.
  • Using a normal function inside a method callback. this is lost inside it. Use an arrow function.
  • **Assuming this is the function.** It is not. It is the context for the call.
  • Reading this inside a plain function in a module. It is undefined.

Try it yourself

  1. Create a person object with a name and a sayName() method. Extract the method into a variable and call it. What happens? Fix it with bind.
  2. Write the same fix using an arrow function wrapper.
  3. Use call to run introduce for two different objects.
  4. Write a Stopwatch class whose start() method uses setInterval with an arrow function to count seconds.
javascript
const user = {
  name: "Sara",
  greet() {
    return `Hi, I am ${this.name}`;
  },
};

console.log(user.greet()); // Hi, I am Sara

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account