JavaScript Public Instance Fields and Shared Methods
Quick answer
Public instance fields are initialized as own properties of each new instance, unlike ordinary prototype methods.
How it works
A field initializer runs for each instance. A field without an initializer has value undefined. A function-valued field creates an own callable; an ordinary method is shared through the prototype. Public field definition uses own-property definition semantics, not an ordinary assignment to an inherited setter. Base fields initialize before the constructor body; derived fields are explored shortly.
class Bag { items = []; add(n) { this.items.push(n); } }const a = new Bag(); const b = new Bag(); a.add(7);console.log(a.items.length,b.items.length,a.add===b.add);Expected output in Node.js:
1 0 trueThe array is per instance; the method is shared.
class Box { n; read = () => this.n; method() { return this.n; } }const a = new Box(); const b = new Box();console.log(Object.hasOwn(a,"n"),a.read===b.read,a.method===b.method);Expected output in Node.js:
true false trueFields are own; an arrow initializer creates distinct functions.
Common mistakes
An array-valued field initializer creates a fresh array per construction, unlike placing one array on a shared prototype.
Practice
Compare the method identity and array identity of two Bag instances.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Public Instance Fields and Shared Methods — Knowledge Check
Apply the taught concept and predict the output.
Where does a public instance field live?
What is the initial value of a public field without an initializer?
What happens to an array field initializer across two constructions?
What is the exact console output in JavaScript Public Instance Fields and Shared Methods example 1?
class Bag { items = []; add(n) { this.items.push(n); } }const a = new Bag(); const b = new Bag(); a.add(7);console.log(a.items.length,b.items.length,a.add===b.add);What is the exact console output in JavaScript Public Instance Fields and Shared Methods example 2?
class Box { n; read = () => this.n; method() { return this.n; } }const a = new Box(); const b = new Box();console.log(Object.hasOwn(a,"n"),a.read===b.read,a.method===b.method);