Reading history

The this Keyword in JavaScript: call, apply, bind and Arrow Functions

5 min read 0 views

Understand JavaScript this: how the call site sets it, losing this in callbacks, call, apply and bind, and how arrow functions inherit this.

Inside a function, the keyword this refers to an object, but which object is decided only when the function is called, not when it is written. The same method can see a different this depending on how it is invoked, which is the source of many confusing bugs. This lesson explains the rules, how call, apply and bind control this, and why arrow functions behave differently.

In this lesson you will learn

  • How the call site decides the value of this
  • Why a method “loses” this when passed around
  • Setting this with call, apply and bind
  • How arrow functions inherit this
  • Common fixes in classes and event handlers

This lesson builds on Functions and Objects.

this Depends on the Call

"use strict";
// "this" depends on HOW a function is called
const student = {
  name: "Mitu",
  greet() {
    return "Hi, I am " + this.name;
  },
};
console.log(student.greet());            // called on student: this = student

const loose = student.greet;
try {
  console.log(loose());                  // called alone: this is undefined in strict mode
} catch (e) {
  console.log("Error:", e.message);
}

// call, apply and bind set "this" explicitly
function introduce(city, year) {
  return `${this.name} from ${city}, class of ${year}`;
}
const tanvir = { name: "Tanvir" };
console.log(introduce.call(tanvir, "Sylhet", 2027));
console.log(introduce.apply(tanvir, ["Khulna", 2028]));
const bound = introduce.bind(tanvir, "Rajshahi");
console.log(bound(2029));

Output

Hi, I am Mitu
Error: Cannot read properties of undefined (reading 'name')
Tanvir from Sylhet, class of 2027
Tanvir from Khulna, class of 2028
Tanvir from Rajshahi, class of 2029
  • student.greet() is a method call: the object before the dot becomes this.
  • Copying the method into a variable and calling loose() loses that object. In strict mode (and in modules and classes, which are always strict) this is undefined, so reading this.name throws a TypeError. In old non-strict scripts it would silently be the global object instead.
  • fn.call(obj, a, b) calls the function once with this set to obj, passing arguments one by one.
  • fn.apply(obj, [a, b]) does the same but takes the arguments as an array.
  • fn.bind(obj, a) does not call anything. It returns a new function with this (and here the first argument) permanently fixed.

Arrow Functions and this

"use strict";
// Arrow functions do not have their own "this"
class Timer {
  constructor() {
    this.seconds = 0;
  }
  tickRegular() {
    [1, 2, 3].forEach(function () {
      try { this.seconds++; } catch (e) { console.log("regular function:", e.constructor.name); }
    });
  }
  tickArrow() {
    [1, 2, 3].forEach(() => { this.seconds++; });   // uses Timer's this
    console.log("arrow function: seconds =", this.seconds);
  }
}
const t = new Timer();
t.tickRegular();
t.tickArrow();

// Arrow functions as object methods are a trap
const counter = {
  count: 10,
  regular() { return this.count; },
  arrow: () => this.count,      // "this" is NOT counter here
};
console.log(counter.regular());
console.log(counter.arrow());

Output

regular function: TypeError
regular function: TypeError
regular function: TypeError
arrow function: seconds = 3
10
undefined
  • A regular function passed to forEach is called on its own, so its this is undefined and the code fails three times.
  • An arrow function has no this of its own; it uses the this of the surrounding code. Inside tickArrow that is the Timer instance, so the count reaches 3. This is why arrow functions are ideal for callbacks inside methods.
  • The flip side: an arrow function used as a method does not get the object as this, so counter.arrow() returns undefined. Write methods with the short name() {} syntax.

The Rules at a Glance

How the function is calledValue of this
obj.method()obj
fn() (plain call, strict mode)undefined
fn.call(x), fn.apply(x), fn.bind(x)()x
new Fn()The newly created object
Arrow functionWhatever this is where the arrow was written
DOM handler el.addEventListener("click", function () {})The element (el)

Common Mistakes

  1. Passing a method as a callback, such as setTimeout(obj.save, 1000); use () => obj.save() or obj.save.bind(obj).
  2. Writing object methods as arrow functions, which never see the object.
  3. Using this in an arrow event handler and expecting the element; use event.currentTarget instead.
  4. Thinking this means “the function itself”; it never does.

Practice Exercises

Exercise 1. Fix this code so it prints “Saving draft” after one second.

const doc = { title: "draft", save() { console.log("Saving " + this.title); } };
setTimeout(doc.save, 1000);
Show answer
setTimeout(() => doc.save(), 1000);
// or: setTimeout(doc.save.bind(doc), 1000);

Exercise 2. Use Math.max with apply to find the largest number in [4, 19, 7], then do it with spread syntax.

Show answer
const nums = [4, 19, 7];
console.log(Math.max.apply(null, nums));  // 19
console.log(Math.max(...nums));           // 19, the modern way

Frequently Asked Questions

Should I always use arrow functions to avoid this problems?

Use arrow functions for callbacks, and regular method syntax for object and class methods. Each solves a different case, and mixing them up causes the bugs shown above.

What is this at the top level of a script?

In a classic browser script it is the window object. In a module it is undefined. Avoid relying on either.

Summary

  • this is set by how a function is called.
  • Methods lose this when detached; strict mode makes it undefined.
  • call and apply call with a chosen this; bind makes a fixed copy.
  • Arrow functions borrow this from their surroundings.

Next: Prototypes and Inheritance.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *