Skip to content
dreamcode
dreamcode
Map
this
Lesson 30 of 48
+15 XP on finish
JS FUNCTIONSChapter 5 · JS Functions and Classes

Understanding this

this is decided by how a function is called. Called as obj.method(), this is obj. Pull the method out and call it on its own, and this is lost. Arrow functions do not have their own this; they use the this of the code around them, which makes them ideal for callbacks inside methods. fn.bind(obj) returns a copy of a function with this locked to obj.

Worked example

How it reads

  • ship.greet() is called on ship, so this is ship
  • The arrow callback in countdown borrows this from the method
  • bind makes a new function whose this is fixed
Common mistakes
  • A regular function callback inside a method gets its own this, so this.count no longer points at your object.
Cloud tip: Inside a method, use an arrow function for any callback that needs this.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

The callback loses this, so the count stays at 0. Rewrite the callback as an arrow function so start() counts all three items and prints 3.

Press Run to check your work.