What is "this" in JavaScript?

Understanding how the value of this is decided in JavaScript.

There are times when you write a method that works perfectly, then you pass it to setTimeout or an event listener and suddenly this is undefined. That's because this in JavaScript isn't decided where a function is written. It's decided by how the function is called.

TL;DR this is the object a function was called on. Look at the call site, not the function definition, to figure out what it is. Arrow functions are the exception: they use the this of the code around them.

There are a handful of rules. Once you know them, this stops being a mystery.

1. Default binding

When you call a plain function on its own, there's no object to the left of the dot. In strict mode, this is undefined. In sloppy (non-strict) mode, it falls back to the global object, window in the browser.

function showThis() {
"use strict"
console.log(this)
}
showThis() // console: undefined

ES modules and class bodies are always in strict mode, so in modern code you'll usually get undefined here.

2. Method call

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

const user = {
name: "John",
greet() {
return `Hi, I'm ${this.name}`
},
}
user.greet() // "Hi, I'm John"

It's the call that matters, not where the function lives. Copy the method to another object and this changes with it:

const admin = { name: "Jane", greet: user.greet }
admin.greet() // "Hi, I'm Jane"

3. The new keyword

When you call a function with new, JavaScript creates a brand new object and sets this to it. This is how constructors and classes set up their instances.

class User {
constructor(name) {
this.name = name
}
}
const user = new User("John")
user.name // "John"

4. Explicit binding with call, apply and bind

You can choose this yourself. call and apply run the function right away with the this you pass in. The only difference is how they take arguments. bind doesn't run the function. It returns a new function with this locked in.

function introduce(greeting, punctuation) {
return `${greeting}, I'm ${this.name}${punctuation}`
}
const user = { name: "John" }
introduce.call(user, "Hello", "!") // "Hello, I'm John!"
introduce.apply(user, ["Hey", "."]) // "Hey, I'm John."
const introduceJohn = introduce.bind(user)
introduceJohn("Hi", "?") // "Hi, I'm John?"

5. Arrow functions

Arrow functions don't get their own this. They use the this of the scope they were created in, and call, apply and bind can't change it.

const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++
console.log(this.seconds)
}, 1000)
},
}
timer.start() // console: 1, 2, 3...

The arrow function inside start uses the same this as start, which is timer. A regular function there would have lost it. Because of this, avoid arrow functions for object methods. An arrow function as greet on an object literal won't see the object at all.

The common pitfall: losing this in callbacks

The most common this bug happens when you pass a method somewhere as a callback. You're passing the function, not the object, so the method call rule no longer applies.

class Counter {
count = 0
increment() {
this.count++
console.log(this.count)
}
}
const counter = new Counter()
setTimeout(counter.increment, 1000)
// TypeError: Cannot read properties of undefined (reading 'count')

setTimeout calls increment as a plain function later on, so this is undefined (class bodies are strict). Event listeners have a similar problem. With a regular function, this is set to the element the listener is attached to:

const button = document.querySelector("button")
button.addEventListener("click", counter.increment)
// this is the button, so this.count is NaN after ++

There are a few ways to fix this.

Wrap the call in an arrow function so it's called as a method again:

setTimeout(() => counter.increment(), 1000)
button.addEventListener("click", () => counter.increment())

Use bind to create a version with this locked in:

setTimeout(counter.increment.bind(counter), 1000)

Or define the method as an arrow function class field, so each instance gets its own copy bound to that instance:

class Counter {
count = 0
increment = () => {
this.count++
console.log(this.count)
}
}
const counter = new Counter()
button.addEventListener("click", counter.increment) // works

The class field approach is common in event-heavy code. The tradeoff is that the function is created per instance instead of being shared on the prototype.

Note: If you need to remove an event listener later, keep a reference to the bound function. Calling bind twice gives you two different functions.

Summary

To figure out this, look at how the function is called: on its own, as a method, with new, or with call, apply or bind. Arrow functions skip all of that and use the this around them, which is exactly why they're the go-to fix for callbacks.

Have some feedback on this post? .