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”
thiswhen passed around - Setting
thiswithcall,applyandbind - 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 becomesthis.- Copying the method into a variable and calling
loose()loses that object. In strict mode (and in modules and classes, which are always strict)thisisundefined, so readingthis.namethrows aTypeError. In old non-strict scripts it would silently be the global object instead. fn.call(obj, a, b)calls the function once withthisset toobj, 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 withthis(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
functionpassed toforEachis called on its own, so itsthisisundefinedand the code fails three times. - An arrow function has no
thisof its own; it uses thethisof the surrounding code. InsidetickArrowthat is theTimerinstance, 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, socounter.arrow()returnsundefined. Write methods with the shortname() {}syntax.
The Rules at a Glance
| How the function is called | Value 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 function | Whatever this is where the arrow was written |
DOM handler el.addEventListener("click", function () {}) | The element (el) |
Common Mistakes
- Passing a method as a callback, such as
setTimeout(obj.save, 1000); use() => obj.save()orobj.save.bind(obj). - Writing object methods as arrow functions, which never see the object.
- Using
thisin an arrow event handler and expecting the element; useevent.currentTargetinstead. - Thinking
thismeans “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
thisis set by how a function is called.- Methods lose
thiswhen detached; strict mode makes itundefined. callandapplycall with a chosenthis;bindmakes a fixed copy.- Arrow functions borrow
thisfrom their surroundings.
Next: Prototypes and Inheritance.
