Classes and this
this
A reference to the object a function was called "on behalf of": the one before the dot.
Why it exists
Methods are written once but work with a thousand objects. A cart's add method must change that cart, the one it was called on — but the method's code doesn't know its name. this is that "that one": a hidden parameter JavaScript fills in at the call. Without it you'd pass the object by hand: add(cart, "fish") — which, by the way, is how languages without methods do it.
Where it's used
- Methods of classes and objects:
this.items.push(item)in a cart,this.hp -= damageon a character. - Constructors:
this.name = namefills in the new object on new. - Event handlers: in
button.addEventListener("click", function () { … })thisis the button; React class components usethis.stateandthis.props. - Binding callbacks:
setTimeout(this.tick.bind(this), 1000)or an arrow() => this.tick().
Syntax
obj.method(); // this === obj
new Class(); // this is the new object
const bound = fn.bind(obj); // this is always obj
() => this // this from outsideExamples
const robot = {
name: "Bolt",
hello() {
return "I am " + this.name;
},
};
robot.hello(); // → "I am Bolt"
const other = { name: "Nutty", hello: robot.hello };
other.hello(); // → "I am Nutty"const counter = {
clicks: 0,
click() {
this.clicks += 1;
return this.clicks;
},
};
const handler = counter.click.bind(counter);
handler(); // → 1
handler(); // → 2
counter.clicks; // → 2bind makes a copy of the function with this fixed forever — safe to hand out as a callbackclass Timer {
constructor() {
this.ticks = 0;
}
run() {
[1, 2, 3].forEach(() => {
this.ticks += 1;
});
return this.ticks;
}
}
new Timer().run(); // → 3this — the callback changes the right objectResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A function in JavaScript is an ordinary value. You can put it in a property of one object, of another, in a variable, pass it as an argument. So a function doesn't "belong" to an object, and this can't be baked in when it's written. It's decided by each call:
obj.method()—thisisobj;- plain
fn()—thisis undefined in strict mode (and class code is always strict); in old sloppy code, the global object; new Fn()—thisis the new object;fn.call(obj),fn.apply(obj),fn.bind(obj)—thisis set explicitly.
Arrow functions are the exception: they have no this of their own and see the this of the place they were created, like an ordinary outer variable. That's why an arrow inside a method is perfect for a callback (forEach, setTimeout), but a poor choice for the object's method itself.
It works this way because JavaScript was made to look like Java on the outside, while inside it borrowed from Scheme and Self, where functions live on their own. Methods arrived as "a function in a property", and this as a way to know which property it was called through.
Traps
How it differs from…
- Arrow functions
A regular function gets
thisfrom the call, an arrow from the surrounding code. The method is a regular function; the callback inside the method is an arrow.
When to pick something else
If a function doesn't need an object, leave this alone — pass data as parameters: total(items) is clearer and easier to test. Don't use this in functions that are called on their own, and don't rely on sloppy mode, where this silently becomes the global object.
Practice
Lessons where this appears
- Byte's robot factoryTale · Chapter 14 · this and classes
- Why does this get lost?Why? · Chapter 14 · this and classes
- The case of the deaf remoteInvestigation · Chapter 14 · this and classes
- Rusty MegabotBoss · Chapter 14 · this and classes
- The shop window that purrsTale · Chapter 19 · Events
- Five ticketsWorkshop · Chapter 26 · Debugging