Sub topic 11
this in Classes and Class Fields
This chapter assumes you already know the binding rules from earlier chapters: implicit binding, lost bindings, bind, new, and lexical this in arrow functions. Here we apply them to class syntax, where the rules behave the same way but some defaults are different.
Class Bodies Are Always Strict
All code inside a class body runs in strict mode, even if the file has no 'use strict' directive. So when a class method loses its object, this becomes undefined. It never falls back to globalThis. The good side is that a lost binding fails loudly with a TypeError. It does not quietly read or write global properties.
Inside a constructor, this is the new instance, because classes can only be called with new. If you call a class without new, it throws a TypeError.
Prototype Methods vs Arrow Class Fields
A method written with method syntax lives once on the prototype, and every instance shares it. A class field holding an arrow function is created per instance, inside the constructor, so the arrow captures that instance as its lexical this.
class Button {
label = 'Save';
handleClick = () => {
console.log(this.label);
};
logLabel() {
console.log(this.label);
}
}
const btn = new Button();
const { handleClick, logLabel } = btn;
handleClick(); // 'Save', the arrow field captured the instance
try {
logLabel(); // class code is strict, so this is undefined
} catch (err) {
console.log(err instanceof TypeError); // true
}Three Ways to Keep this
There are three common ways to make sure a method keeps its this:
| Approach | Where it lives | Survives extraction | Overridable via `super` | Cost |
|---|---|---|---|---|
| Prototype method | Prototype, shared | No | Yes | One function total |
| `this.m = this.m.bind(this)` in constructor | Instance (bound copy) | Yes | Yes, the prototype version still exists | One bound function per instance |
| Arrow class field | Instance | Yes | No, there is nothing on the prototype | One function per instance |
Binding in the constructor gives you the best of both. The real method stays on the prototype, where subclasses can override it, and each instance gets a bound wrapper:
class Counter {
count = 0;
constructor() {
this.increment = this.increment.bind(this);
}
increment() {
this.count++;
return this.count;
}
}
const c = new Counter();
const inc = c.increment;
console.log(inc()); // 1
console.log(inc()); // 2this in Subclasses
In a derived class, this does not exist until super() returns, because the base constructor is the one that creates the object. If you touch this before calling super(), you get a ReferenceError.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name) {
// this.tricks = []; // ReferenceError if placed here
super(name);
this.tricks = [];
}
speak() {
return `${super.speak()} (woof)`;
}
}
console.log(new Dog('Rex').speak()); // 'Rex makes a sound (woof)'super.speak() runs the parent's method with the current this, so this.name inside Animal.prototype.speak reads the Dog instance.
Field initializers in a subclass also run right after super() returns. This causes a common trap. If a base constructor calls a method that a subclass defines as an arrow field, the field does not exist yet:
class Base {
constructor() {
console.log(typeof this.init); // 'undefined' when init is a subclass field
}
}
class Child extends Base {
init = () => 'ready';
}
new Child(); // logs 'undefined'Common Errors
Cannot read properties of undefinedfrom a method passed as a callback. You extracted a prototype method. Fix it with an arrow field, a constructorbind, or a wrapper like() => obj.method()at the call site.Must call super constructor before accessing 'this'. You usedthisbeforesuper()in a derived constructor.super.handler is not a function. The parent definedhandleras an arrow field, not a method.
Exercise
A class defines save() { return this.id; } as a prototype method. You pass instance.save to setTimeout, and it throws. Give two fixes inside the class and one at the call site, and say which in-class fix still lets a subclass call super.save().
Show answer
Inside the class you can turn save into an arrow field (save = () => this.id;), or add this.save = this.save.bind(this); in the constructor. At the call site you can write setTimeout(() => instance.save()) or setTimeout(instance.save.bind(instance)). Only the constructor bind keeps save on the prototype, so it is the in-class fix that still lets a subclass call super.save().
Exercise
What does new Child() log, and why? class Base { constructor() { this.hello(); } hello() { console.log('base'); } } class Child extends Base { hello() { console.log('child'); } }
Show answer
It logs 'child'. hello is a prototype method, so it already exists on Child.prototype while the base constructor runs. this.hello() looks it up through the instance's prototype chain and finds the override. If Child had declared hello as an arrow field instead, the field would not exist yet, and 'base' would be logged.