How to Fix "this is undefined" Error in JavaScript Classes
- Author
- Sean Keever
- Last modified
- Jan 23, 2021
- Time to read
- 1 min read
Photo by Ray Hennessy
Table of Contents
Context
Suppose we have an Adder
classes that can take an array of numbers and add each number by x
.
class Adder {
private readonly x: number
constructor(x: number) {
this.x = x
}
addAll(ns: number[]) {
return ns.map(this.add)
}
private add(n: number) {
return this.x + n
}
}
Problem
When we run this code, we get an error that this
is undefined.
new Adder(2).addAll([1, 2, 3])
// Uncaught TypeError: Cannot read property 'x' of undefined
Why is this? I think it's because when we pass the function directly into map
, we are
getting a reference to the method belonging to the class, not the method belonging to the class instantiation.
Solution
Luckily, the fix is simple: wrap your function in a higher order function.
class Adder {
// ...
addAll(ns: number[]) {
return ns.map((n) => this.add(n)) }
// ...
}
Now when we run our sample client, this
is defined in the private helper method and we don't get the error.
new Adder(2).addAll([1, 2, 3])
// [3, 4, 5]
Hopefully this helps you save some time debugging.
- Author
- Sean Keever
- Last modified
- Jan 23, 2021
- Time to read
- 1 min read