Understanding this in JavaScript
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- 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 called | Value 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 function | this 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.methodas a callback.** Wrap it in an arrow function or usebind. - Using an arrow function for an object method.
thiswill not point to the object. - Using a normal function inside a method callback.
thisis lost inside it. Use an arrow function. - **Assuming
thisis 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
- Create a
personobject with anameand asayName()method. Extract the method into a variable and call it. What happens? Fix it withbind. - Write the same fix using an arrow function wrapper.
- Use
callto runintroducefor two different objects. - Write a
Stopwatchclass whosestart()method usessetIntervalwith an arrow function to count seconds.
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