Sub topic 6
Declaring Public Instance Fields
This chapter assumes you already know how to write a class with a constructor and instance methods. It also assumes you are comfortable with this inside a constructor.
What a field declaration is
A public instance field is a property that you declare directly in the class body. Each new instance gets that property as its own property. You don't have to assign it in the constructor.
class Cart {
items = [];
discount = 0;
createdAt = Date.now();
note;
constructor(discount) {
if (discount !== undefined) {
this.discount = discount;
}
}
add(item) {
this.items.push(item);
return this;
}
}
const a = new Cart();
const b = new Cart(10);
a.add('apple');
console.log(a.items, b.items); // [ 'apple' ] []
console.log(b.discount); // 10
console.log(a.note); // undefined
console.log(Object.hasOwn(a, 'items')); // trueEach field is a name with an optional initializer. If a field has no initializer, as with note above, the property still exists and its value is undefined. A field declaration uses no let, const, or var. Writing let items = []; in a class body is a syntax error.
Initializers run once per instance
JavaScript evaluates a field initializer each time it creates an instance. That is why a.items and b.items above are separate arrays. A method lives once on the prototype, but a field becomes an own property on every object. This also means that each instance pays for its own copy of every field, so keep bulky shared data out of fields.
When fields are initialized
In a base class, fields are set up before the constructor body runs. They are added in the order they are written, so an initializer can read fields declared above it through this.
class Order {
price = 20;
tax = this.price * 0.1;
early = this.late;
late = 'set';
constructor() {
console.log(this.price, this.tax); // 20 2
console.log(this.early); // undefined
}
}
new Order();early reads this.late before late exists, so it gets undefined. JavaScript throws no error here, which makes this bug easy to miss.
In a subclass, fields are initialized right after super() returns. A later chapter on super covers this.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Referencing a field declared later | Value is `undefined` | Reorder the fields, or compute the value in the constructor |
| Needing a constructor argument in an initializer | Initializers can't see constructor parameters | Give a default in the field, then assign it in the constructor |
| Expecting a parent's setter to run | Fields are *defined*, not assigned, so the setter is skipped | Assign the value in the constructor instead |
The last row trips people up most often:
class Base {
set label(v) { console.log('setter called'); }
}
class Child extends Base {
label = 'hi';
}
const c = new Child(); // no log
console.log(Object.hasOwn(c, 'label')); // trueA field creates an own data property, like Object.defineProperty. That own property shadows the accessor that Child inherits from Base.
Exercise
Given class T { a = this.b + 1; b = 2; }, what is new T().a, and why?
Show answer
It is NaN. Fields initialize top to bottom, so when a is computed, this.b is still undefined, and undefined + 1 is NaN. Declaring b before a makes a equal 3.
Exercise
Two instances of class Bag { items = []; } are created and one pushes a value into its items. Does the other instance see it?
Show answer
No. The initializer [] is evaluated separately for each instance, so each one has its own array.