Why does this get lost?
Why this is decided at call time, and how not to lose it.
cleaner.clean(), everything worked. I handed the same method to a timer — TypeError: Cannot read properties of undefined. The same code! Where did this go?Let's start from afar. In JavaScript a function is an ordinary value, like a number or a string. A method is just a property that holds a function. Which means one and the same function can sit in two objects at once — and "belong" to neither.
function introduce() {
return "I am " + this.name;
}
const a = { name: "Bolt", introduce };
const b = { name: "Nutty", introduce };
console.log(a.introduce());
console.log(b.introduce());
console.log(a.introduce === b.introduce);this.Since the function belongs to nobody, this can't be baked into it when it's written. Each call picks it:
const cleaner = {
room: "the kitchen",
clean() {
return "Cleaning: " + this.room;
},
};
console.log(cleaner.clean());
const job = cleaner.clean;
console.log(job());job() is a call without a dot. this is no longer cleaner, and the room is gone.That's exactly what happened with the timer. setTimeout(cleaner.clean, 1000) receives only the function — the object is left behind. A second later the timer calls it as fn(), without a dot. The same goes for click handlers: button.onclick = cart.clear.
There are two cures:
const cleaner = {
room: "the kitchen",
clean() {
return "Cleaning: " + this.room;
},
};
// Like setTimeout, but calls right away
function later(task) {
return task();
}
console.log(later(() => cleaner.clean()));
console.log(later(cleaner.clean.bind(cleaner)));this.And why does an arrow help? Arrow functions have no `this` of their own. They see the this of the place they were created, like an ordinary outer variable. That's why an arrow inside a method is the perfect callback: its this is the method's this.
class Factory {
constructor() {
this.built = 0;
}
buildAll(names) {
names.forEach(() => {
this.built += 1;
});
return this.built;
}
}
console.log(new Factory().buildAll(["Bolt", "Nutty", "Screwy"]));forEach takes this from the buildAll method. With function () { … } you'd get a TypeError here.One last thing: classes don't change any of this. class arrived in 2015 as a convenient syntax over prototypes: methods live in Robot.prototype, and bolt.hello simply finds the function there. The function still belongs to nobody — the this rules are the same. The only difference: class code is always strict, so a lost this gives an immediate TypeError instead of a quiet undefined. And that's a good thing: you see the bug right away.
this. No dot — no this. Handing a method to someone else — wrap it in an arrow.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.