Sub topic 6
Declaring Public Instance Fields
This chapter assumes you already know how a constructor sets properties with this.x = ... and that methods live on the class's prototype. It also uses extends and super() in a few short previews. Later chapters explain those two in full. Here you only need to know that a subclass constructor must call super() before it can use this.
A public instance field is a property you declare directly in the class body. Each instance gets its own copy, created when the instance is built. Fields let you list an object's shape in one place, and you no longer need a constructor just to assign default values.
Field Syntax
A field declaration is a name, an optional = with an initializer expression, and a semicolon. Leave out the initializer and the field still exists, with the value undefined.
class Todo {
title = 'Untitled';
done = false;
tags = [];
createdAt = Date.now();
notes;
}
const t1 = new Todo();
const t2 = new Todo();
t1.tags.push('home');
console.log(t2.tags); // []
console.log(Object.hasOwn(t1, 'done')); // true
console.log('notes' in t1, t1.notes); // true undefined
console.log(Object.keys(t1)); // ['title', 'done', 'tags', 'createdAt', 'notes']The engine runs the initializer once for each instance. That is why t1.tags and t2.tags are separate arrays. If you put an array on the prototype instead, every instance would share it. Fields are own, enumerable properties, so they show up in Object.keys, in spread syntax, and in JSON.stringify.
What `this` Means in an Initializer
Inside a field initializer, this is the instance under construction. An initializer can therefore read fields declared above it and call methods, because methods already exist on the prototype.
class Person {
first = 'Ada';
last = 'Lovelace';
fullName = `${this.first} ${this.last}`;
early = this.later; // later has not been initialized yet
later = 'set';
}
const p = new Person();
console.log(p.fullName); // 'Ada Lovelace'
console.log(p.early); // undefinedFields are initialized from top to bottom, in source order. When you read a field before its own initializer has run, you get undefined and no error is thrown. This bug is easy to miss.
Initializers cannot see the constructor's parameters. The parameters belong to the constructor's scope, and fields are evaluated outside that scope.
class Broken {
radius = r; // ReferenceError: r is not defined (when new runs)
constructor(r) {}
}
class Circle {
radius; // declares the shape
constructor(r) {
this.radius = r; // assigns from the argument
}
}
console.log(new Circle(2).radius); // 2A common pattern is to declare the field without an initializer, so the class body documents the shape, and then assign the value in the constructor.
Initialization Order
When fields are initialized depends on whether the class extends another class.
- In a base class (one with no
extends), fields are initialized right at the start of the constructor, before the first line of the constructor body runs. - In a derived class, fields are initialized as soon as
super()returns. Before that point,thisdoes not exist yet.
class Order {
log = [];
first = this.record('first field');
constructor() {
this.record('constructor body');
}
record(msg) {
this.log.push(msg);
return msg;
}
second = this.record('second field');
}
console.log(new Order().log);
// ['first field', 'second field', 'constructor body']The field second appears in the source after the constructor, yet it still runs before the constructor body. The position of the constructor in the class body has no effect on the order.
The derived ordering causes a well-known gotcha. While the parent constructor runs, the subclass's fields do not exist yet.
class Base {
constructor() {
console.log('Base sees kind =', this.kind);
this.describe();
}
describe() {}
}
class Derived extends Base {
kind = 'derived';
describe() {
console.log('describe sees kind =', this.kind);
}
constructor() {
super();
console.log('After super, kind =', this.kind);
}
}
new Derived();
// Base sees kind = undefined
// describe sees kind = undefined
// After super, kind = derivedThe overridden describe method runs on the derived instance, but kind has not been initialized yet. The rule is simple: a parent constructor should not rely on subclass fields, whether it reads them directly or through methods that a subclass might override.
Define Semantics, Not Assignment
A field creates its property the way Object.defineProperty does. It does not use ordinary assignment. The difference matters when an inherited setter has the same name as the field.
class Base {
set color(v) {
console.log('setter ran with', v);
}
}
class WithAssign extends Base {
constructor() {
super();
this.color = 'red'; // assignment: finds and calls the inherited setter
}
}
class WithField extends Base {
color = 'red'; // definition: creates an own property, setter skipped
}
new WithAssign(); // setter ran with red
const w = new WithField(); // no output
console.log(Object.getOwnPropertyDescriptor(w, 'color'));
// { value: 'red', writable: true, enumerable: true, configurable: true }The field creates a plain data property on the instance. That property shadows the accessor on the prototype, so the setter never runs, not even on later assignments to w.color. This catches people who migrate from this.x = ... in a constructor to field syntax, and it catches TypeScript users who switch on useDefineForClassFields. If a parent class exposes an accessor, assign to it in the constructor. Do not redeclare it as a field.
A field also shadows a method that has the same name:
class Widget {
render = null;
render() {
return 'drawn';
}
}
const wd = new Widget();
console.log(wd.render); // null
console.log(Widget.prototype.render.call(wd)); // 'drawn'Computed Field Names
A field name can be computed with brackets. The engine evaluates the key expression once, when the class is defined. It evaluates the initializer once for each instance.
const key = 'status';
let defs = 0;
class Job {
[key] = 'pending';
[(defs++, 'retryCount')] = 0;
}
new Job();
new Job();
console.log(new Job().status, defs); // 'pending' 1Symbols work as keys too. Writing [Symbol.toStringTag] = 'Job'; gives each instance its own tag property.
Choosing Where a Property Lives
| Approach | Where it lives | Per-instance copy | Can use constructor args | Triggers inherited setters |
|---|---|---|---|---|
| Field `x = value;` | Instance | Yes | No | No |
| `this.x = value` in constructor | Instance | Yes | Yes | Yes |
| Method `x() {}` | Prototype | No, shared | Not applicable | Not applicable |
| Arrow function field `x = () => {}` | Instance | Yes, one function per instance | No | No |
Arrow function fields capture this permanently, and the chapter on this binding uses that property. The cost is one function object per instance, while a method stores a single function on the prototype. A class with 10,000 instances and an arrow field holds 10,000 function objects. Use arrow fields for callbacks that really get detached from their object, and use methods for everything else.
Common Errors at a Glance
- Reading a later field from an earlier initializer gives
undefined. - Referring to a constructor parameter from an initializer throws a ReferenceError.
- Redeclaring an inherited accessor as a field silently bypasses the setter.
- A parent constructor that reads subclass fields sees
undefined. - Using
let,const, or commas in the class body is a SyntaxError.
Exercise
What does this code log, and why? class A { constructor() { console.log(this.n); } } class B extends A { n = 5; } new B();
Show answer
It logs undefined. The fields of B are initialized only after super() returns. The implicit B constructor calls super(), A's constructor runs and reads this.n, and the n field does not exist yet at that moment.
Exercise
A class Base defines "set value(v) { this.v = v * 2; }". A subclass declares the field "value = 10;". Then the code runs "const s = new Sub(); s.value = 4;". What are s.value and s.v?
Show answer
s.value is 4 and s._v is undefined. The field defines an own data property named value, which shadows the inherited setter. The field initialization and the later assignment both write to that data property, so the setter never runs.
Exercise
Rewrite this class so it works: class Rect { width = w; height = h; area = this.width * this.height; constructor(w, h) {} }
Show answer
Declare the fields and assign them in the constructor: class Rect { width; height; area; constructor(w, h) { this.width = w; this.height = h; this.area = w * h; } }. Field initializers cannot see the parameters w and h, so those values must be assigned inside the constructor. A getter for area would also stay correct if width or height changes later.