Sub topic 11
this in Classes and Class Fields
This chapter assumes you already know the binding rules from the earlier chapters: default binding, implicit binding, call/apply/bind, new, and lexical this in arrow functions. You should also be comfortable with class syntax and extends. Classes add no new binding rule. They combine the existing rules in ways that are easy to misread. Each section below covers one piece: where methods live, when this exists inside constructors, when class fields run, and how to choose a way to keep this attached.
Class Code Is Always Strict
Everything inside a class body runs in strict mode. That covers the constructor, methods, getters, setters, static members, and field initializers. You do not need a 'use strict' directive. So when a class method loses its object, this becomes undefined, not globalThis. You get a loud TypeError instead of a silent write to a global.
class Counter {
count = 0;
increment() {
this.count++;
return this.count;
}
}
const c = new Counter();
console.log(c.increment()); // 1
// The method lives on the prototype, not on the instance
console.log(Object.hasOwn(c, 'increment')); // false
console.log(typeof Counter.prototype.increment); // 'function'
const inc = c.increment;
try {
inc();
} catch (e) {
console.log(e instanceof TypeError); // true: this is undefined
}The method syntax increment() { ... } puts one function on Counter.prototype, and every instance shares it. The function has no tie to any instance. c.increment() works because of implicit binding: c is the object before the dot. Once you copy the function into inc, nothing is before the dot, and you lose the binding exactly as you would with a plain object literal.
this in the Constructor
new Counter() creates a fresh object whose prototype is Counter.prototype and runs the constructor with this set to that object. That is ordinary new binding. Derived classes work differently.
Derived Constructors Do Not Create this
In a class that uses extends, the derived constructor does not create the object. The base constructor creates it, and this stays uninitialized until super() returns. Reading or writing this before that throws a ReferenceError.
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name) {
// this.tricks = []; // ReferenceError: must call super constructor before accessing 'this'
super(name);
this.tricks = [];
}
}
const d = new Dog('Rex');
console.log(d.name, d.tricks); // 'Rex' []
console.log(d instanceof Dog); // trueThe object comes from the base constructor, but its prototype is still Dog.prototype. This works because new passes the original target (new.target, here Dog) down the chain. A derived constructor must call super() before using this. If it never calls super(), it must return an object of its own, or construction fails.
Class Fields and When They Run
A class field such as count = 0; is not a prototype property. It is an initializer that runs once per instance during construction and defines an own property on the new object. Inside a field initializer, this is the instance being built. That is why handleClick = () => { ... this ... } captures the instance: the arrow function is created while this is the instance, and arrows keep the this of the scope they were created in.
The timing matters:
- In a base class, fields are initialized right after the object is created, before the constructor body runs.
- In a derived class, fields are initialized right after
super()returns, before the rest of the derived constructor body.
This order causes a real gotcha. A base constructor that calls an overridable method can reach subclass code before the subclass's fields exist.
class Base {
name = 'base field';
constructor() {
console.log('Base constructor sees:', this.name);
this.describe();
}
describe() {
console.log('Base describe');
}
}
class Derived extends Base {
label = 'derived field';
constructor() {
super();
console.log('Derived constructor sees:', this.label);
}
describe() {
console.log('Derived describe, label =', this.label);
}
}
new Derived();
// Base constructor sees: base field
// Derived describe, label = undefined
// Derived constructor sees: derived fieldthis.describe() in the base constructor resolves through Derived.prototype, because the instance's prototype is already set. Derived fields have not run yet, so this.label is undefined. The rule of thumb is to avoid calling overridable methods from a constructor. If you must, do not let them depend on subclass fields.
Three Ways to Keep a Method Attached
When a method will be passed around, for example as an event handler, a callback, or a destructured value, you need this to stay fixed. Classes give you three options.
Option 1: Prototype Method, Bind at the Call Site
Keep a normal method and fix this where you hand it off:
class Logger {
prefix = '[app]';
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
}
const logger = new Logger();
['a', 'b'].forEach(logger.log.bind(logger)); // [app] a, [app] b
['c'].forEach((m) => logger.log(m)); // [app] cThere is one function in memory and full inheritance. The cost is that every caller has to remember to bind, and bind returns a new function each time. That matters when you need the same reference later, for example with removeEventListener.
Option 2: Bind in the Constructor
class Base {
name = 'widget';
constructor() {
this.greet = this.greet.bind(this);
}
greet() {
return `base for ${this.name}`;
}
}
class Child extends Base {
greet() {
return `child, then ${super.greet()}`;
}
}
const { greet } = new Child();
console.log(greet()); // 'child, then base for widget'this.greet in the base constructor looks up the prototype chain and finds Child.prototype.greet, so the subclass override is the one that gets bound. super.greet() inside it calls Base.prototype.greet with the current this, which is the instance. Overriding and super calls keep working, and the bound function is a stable reference that you can pass and remove later. The original method also stays on the prototype, so tests can still spy on it.
Option 3: Arrow Function Class Field
class Button {
label = 'Save';
handleClick = () => {
console.log(this.label);
};
}
const { handleClick } = new Button();
handleClick(); // 'Save'This is the shortest form, and you cannot get it wrong at the call site. But handleClick is an own property of each instance, not a prototype method, and that has consequences:
- Each instance allocates its own function. With thousands of instances, that memory adds up.
- A subclass cannot call it through
super, becausesuperlooks on the parent's prototype and the field is not there. - A subclass field with the same name simply replaces it after
super()returns. - Code that patches or spies on
Button.prototype.handleClickmisses it.
class Base {
greet = () => 'base';
}
class Child extends Base {
greet = () => `child, then ${super.greet()}`;
}
try {
new Child().greet();
} catch (e) {
console.log(e instanceof TypeError); // true: super.greet is undefined
}super.greet here reads Base.prototype.greet, which does not exist, because Base's greet is a per-instance field.
Choosing Between Them
| Approach | Memory | Override with super | Stable reference | Risk of lost this |
|---|---|---|---|---|
| Prototype method | One shared function | Yes | No, bind each time | High if passed around |
| Bind in constructor | One bound copy per instance | Yes | Yes | None |
| Arrow class field | One copy per instance | No | Yes | None |
Use plain prototype methods by default, especially for methods that are only called as obj.method(). Use arrow fields for leaf classes, such as UI components, where handlers are passed around and nothing will subclass them. Use constructor binding when you need both a stable reference and inheritance.
this in Static Members
Static methods are called on the class, so implicit binding makes this the constructor function itself. Because derived classes inherit statics through their own prototype chain (Object.getPrototypeOf(User) === Model), this in an inherited static method is whichever class you called it on. That makes static factories work correctly in subclasses.
class Model {
static registry = [];
static kind = this.name; // in a static field, this is the class
static create(...args) {
const obj = new this(...args); // this is the class it was called on
this.registry.push(obj);
return obj;
}
}
class User extends Model {
constructor(name) {
super();
this.name = name;
}
}
const u = User.create('Ada');
console.log(u instanceof User); // true
console.log(Model.kind); // 'Model'
console.log(User.registry === Model.registry); // trueThe last line is a trap. User has no own registry, so this.registry reads the inherited array from Model, and every subclass pushes into one shared list. If each subclass needs its own state, use Object.hasOwn(this, 'registry') to check, or declare the static field again in the subclass. Static methods lose this when detached, the same way instance methods do: const { create } = User; create() throws.
Getters, Setters, and Private Fields
Getters and setters follow the same rule: this is the object the property was accessed on. Private fields add one more check. this.#secret throws a TypeError if this is not an object that the class constructed, so a lost binding fails right away even in places where a public property would just give undefined.
class Account {
#balance = 100;
get balance() {
return this.#balance;
}
report() {
return `Balance: ${this.#balance}`;
}
}
const acct = new Account();
console.log(acct.balance); // 100
const fake = { report: acct.report };
try {
fake.report();
} catch (e) {
console.log(e instanceof TypeError); // true: fake has no #balance
}Here this was bound, but to the wrong object. Private fields turn that silent bug into an error.
Exercise
In the code below, what does new Square(2) log, and why? class Shape { constructor() { console.log(this.area()); } area() { return 0; } } class Square extends Shape { side = 0; constructor(s) { super(); this.side = s; } area() { return this.side * this.side; } }
Show answer
It logs NaN. The Shape constructor calls this.area(), which resolves to Square.prototype.area because the instance's prototype is already Square.prototype. At that moment the Square field side has not been initialized, since derived fields run only after super() returns. So this.side is undefined, and undefined * undefined is NaN.
Exercise
A team has class Panel { onResize = () => { this.layout(); }; layout() {} } and wants class ScrollPanel extends Panel to extend onResize by calling the parent version and then doing extra work. Why does super.onResize() fail, and how should Panel be rewritten?
Show answer
onResize is an arrow class field, so it is an own property of each instance, not a property of Panel.prototype. super.onResize looks on Panel.prototype, finds nothing, and calling undefined throws a TypeError. Rewrite Panel to define onResize() { this.layout(); } as a prototype method and add this.onResize = this.onResize.bind(this); in its constructor. ScrollPanel can then define onResize() { super.onResize(); /* extra */ }. The constructor binding picks up the subclass override and keeps this fixed.
Exercise
Given class Base { static make() { return new this(); } } class Sub extends Base {}, what does Sub.make() instanceof Sub return, and what happens with const { make } = Sub; make();?
Show answer
Sub.make() instanceof Sub is true, because this inside the static method is Sub, the object before the dot. make() called on its own throws a TypeError. Class code is strict, so this is undefined, and new undefined() is not a valid constructor call.