Prototypes & Classes
Published by Brayan K
Prototypes are the objects JavaScript uses to share properties and methods between instances, and classes are cleaner class syntax built on top of that prototype system for creating and inheriting objects.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Separate each object’s data from the behavior it shares
Start by asking where a value lives. An instance can own its data while finding a method through its prototype. A class declaration describes how to initialize instances and where to install their methods; it does not copy every method into every new object.
class Member {
constructor(name) {
this.name = name; // This property belongs to the new instance.
}
label() {
return "Member: " + this.name; // The receiver supplies the data.
}
}
const ada = new Member("Ada");
const mina = new Member("Mina");
console.log(ada.label());
console.log(mina.label());
console.log(Object.hasOwn(ada, "name"));
console.log(Object.hasOwn(ada, "label"));
console.log(ada.label === mina.label);
console.log(Object.getPrototypeOf(ada) === Member.prototype);
// ✅ Expected output:
// Member: Ada
// Member: Mina
// true
// false
// true
// truename is an own property. label is a shared method on Member.prototype. The instance’s internal prototype link is inspected with Object.getPrototypeOf; it is different from looking for a property literally named prototype on the instance.
class Member {}
const member = new Member();
console.log(member.prototype);
console.log(Object.getPrototypeOf(member) === Member.prototype);
console.log(Object.getPrototypeOf(Member.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype) === null);
// ✅ Expected output:
// undefined
// true
// true
// trueOrdinary property lookup first checks the object itself, then its prototype, continuing until it finds the property or reaches null. Prototype Chain & Advanced OOP Patterns owns deeper chain manipulation and advanced inheritance patterns.
Lookup can inherit a value; assignment can shadow it
const defaults = { role: "reader" };
const member = Object.create(defaults);
member.name = "Ada";
console.log(member.role, Object.hasOwn(member, "role"));
member.role = "editor";
console.log(member.role, defaults.role);
console.log(Object.hasOwn(member, "role"));
delete member.role;
console.log(member.role, Object.hasOwn(member, "role"));
// ✅ Expected output:
// reader false
// editor reader
// true
// reader falseFor this ordinary writable data property, assigning member.role creates an own property. It does not edit defaults.role. Deleting the own property reveals the inherited default again. Accessors and non-writable properties have different assignment rules, owned by Getters, Setters & Property Descriptors.
const shared = { tags: [] };
const first = Object.create(shared);
const second = Object.create(shared);
first.tags.push("checked");
console.log(first.tags.join(","));
console.log(second.tags.join(","));
console.log(first.tags === second.tags);
console.log(Object.hasOwn(first, "tags"));
// ✅ Expected output:
// checked
// checked
// true
// falseThe push does not assign first.tags. It changes the array obtained by lookup, and both objects find that same array. Place mutable per-instance state on each instance instead:
class Member {
tags = [];
addTag(tag) { this.tags.push(tag); }
}
const first = new Member();
const second = new Member();
first.addTag("checked");
console.log(first.tags.join(","));
console.log(second.tags.length);
console.log(first.tags === second.tags);
console.log(Object.hasOwn(first, "tags"));
// ✅ Expected output:
// checked
// 0
// false
// trueClass construction and method calls have distinct rules
Use new with a class constructor. It creates the instance and runs initialization. Calling a class as an ordinary function is an error, even when the constructor has no arguments.
class Member {}
Member();
// ✅ Expected error:
// TypeError: Class constructor Member cannot be invoked without 'new'Classes use the prototype system, but class syntax also has its own rules: class bodies run in strict mode, class declarations cannot be used before initialization, and public prototype methods are non-enumerable. Calling classes merely a text substitution for any older constructor function misses those differences.
class Member {
method() { return "shared"; }
arrow = () => "own";
}
const first = new Member();
const second = new Member();
console.log(first.method === second.method);
console.log(first.arrow === second.arrow);
console.log(Object.hasOwn(first, "method"), Object.hasOwn(first, "arrow"));
console.log(Object.keys(Member.prototype).length);
// ✅ Expected output:
// true
// false
// false true
// 0An arrow field creates a function for each instance. Choose it when that behavior is needed, not because all methods should be arrows. Neither form has a universal speed advantage; this example checks placement and identity, not timing.
class Member {
constructor(name) { this.name = name; }
label() { return this.name; }
}
const member = new Member("Ada");
const label = member.label;
console.log(label());
// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'name')Class methods are strict, so this is undefined in that plain call. The this Keyword owns call, bind and arrow receiver rules; preserve the receiver with a wrapper or binding when passing such a method as a callback.
function Member(name) {
this.name = name;
}
Member.prototype.label = function () { return "Member: " + this.name; };
const first = new Member("Ada");
const second = new Member("Mina");
console.log(first.label(), second.label());
console.log(first.label === second.label);
console.log(Object.getPrototypeOf(first) === Member.prototype);
// ✅ Expected output:
// Member: Ada Member: Mina
// true
// trueThis explains the connection to older code. It is not a claim that every constructor-function detail is interchangeable with a class. Prefer Object.getPrototypeOf for inspection; modifying built-in prototypes or replacing a constructor’s prototype after instances exist creates additional consequences outside this introduction.
Static methods belong to the class, not the individual instance
class Member {
constructor(name) { this.name = name; }
static fromRecord(record) {
return new Member(record.name);
}
label() { return this.name; }
}
const member = Member.fromRecord({ name: "Ada" });
console.log(member.label());
console.log(typeof Member.fromRecord);
console.log(typeof member.fromRecord);
console.log(member instanceof Member);
// ✅ Expected output:
// Ada
// function
// undefined
// trueStatic is about where a method is stored. It does not make the result immutable or initialize every instance automatically. This factory deliberately constructs Member; polymorphic factories for subclasses need their own design. Design Patterns owns choosing creation and composition boundaries.
Inheritance shares behavior; super initializes the base part
class Member {
constructor(name) { this.name = name; }
label() { return this.name; }
}
class Editor extends Member {
constructor(name, section) {
super(name);
this.section = section;
}
label() { return super.label() + " / " + this.section; }
}
const editor = new Editor("Ada", "Guides");
console.log(editor.label());
console.log(editor instanceof Editor, editor instanceof Member);
console.log(Object.getPrototypeOf(Editor.prototype) === Member.prototype);
// ✅ Expected output:
// Ada / Guides
// true true
// truesuper(name) runs the base constructor before the derived constructor uses this. super.label() finds the base method while using the current editor as its receiver. Inheritance should describe a relationship your API can honor; it is not required whenever two classes share a few lines.
class Member {}
class Editor extends Member {
constructor() {
this.section = "Guides";
super();
}
}
new Editor();
// ✅ Expected error:
// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructorComposition can be simpler when one object uses another object’s capability rather than being a substitute for it. Design Patterns develops that choice; Prototype Chain & Advanced OOP Patterns owns advanced inheritance behavior.
Private fields enforce access through the declaring class
class Counter {
#count = 0;
increment() { this.#count++; }
read() { return this.#count; }
}
const counter = new Counter();
counter.increment();
console.log(counter.read());
console.log(counter.count);
console.log(counter["#count"]);
console.log(Object.keys(counter).length);
try {
Counter.prototype.read.call({});
} catch (error) {
console.log(error.name);
}
// ✅ Expected output:
// 1
// undefined
// undefined
// 0
// TypeErrorOnly code in the declaring class can name its private field, and a private access also requires a receiver carrying that field. A lookalike plain object is not enough. The caught TypeError name is shown because engines may phrase the full private-field diagnostic differently. Private fields protect the class’s API boundary; they do not make browser-side secrets invisible to the person running the browser.
Getters and setters can provide property-like access to validated state. Getters, Setters & Property Descriptors owns those mechanics. Closures and Scope provides an alternative way for an API to retain local state.
Guided exercise: put data on the instance and behavior on the prototype
Complete the constructor assignment, the new call and the prototype comparison using the literal hints.
class Member {
constructor(name) { this.___ = name; } // 👉 replace ___ with name
label() { return "Member: " + this.name; }
}
const member = ___ Member("Ada"); // 👉 replace ___ with new
console.log(member.label());
console.log(Object.getPrototypeOf(member) === Member.___); // 👉 replace ___ with prototype
// ✅ Expected output:
// Member: Ada
// trueIndependent brief: a reading list with controlled state
Write ReadingList with a private array of titles. add(title) requires a string whose trimmed value is nonempty, otherwise throws TypeError("Title must be a non-empty string"). Store the trimmed title. An exact, case-sensitive duplicate returns false without adding it; a new title returns true. titles() returns a new array, and size() returns the count. A static from(titles) factory accepts an array and adds each item through the same validation; non-arrays throw TypeError("Expected an array").
Check duplicate trimming, independent instances, a modified returned array, valid static creation, an invalid title and a non-array factory input. The list stores strings, so a shallow array copy is sufficient for this contract.
class ReadingList {
#titles = [];
add(title) {
if (typeof title !== "string" || title.trim() === "") {
throw new TypeError("Title must be a non-empty string");
}
const normalized = title.trim();
if (this.#titles.includes(normalized)) return false;
this.#titles.push(normalized);
return true;
}
titles() { return [...this.#titles]; }
size() { return this.#titles.length; }
static from(titles) {
if (!Array.isArray(titles)) throw new TypeError("Expected an array");
const list = new ReadingList();
for (const title of titles) list.add(title);
return list;
}
}
const first = new ReadingList();
const second = new ReadingList();
console.log(first.add(" JavaScript Notes "));
console.log(first.add("JavaScript Notes"));
console.log(first.size(), second.size());
const copy = first.titles();
copy.push("Outside change");
console.log(copy.length, first.size());
console.log(first.titles().join(","));
const made = ReadingList.from(["A", "B", "A"]);
console.log(made instanceof ReadingList, made.size());
console.log(made.titles().join(","));
for (const invalid of [" ", 7]) {
try { first.add(invalid); } catch (error) { console.log(error.message); }
}
try { ReadingList.from("A"); } catch (error) { console.log(error.message); }
console.log("unchanged", first.size());
// ✅ Expected output:
// true
// false
// 1 0
// 2 1
// JavaScript Notes
// true 2
// A,B
// Title must be a non-empty string
// Title must be a non-empty string
// Expected an array
// unchanged 1The static factory delegates to add, so it cannot bypass the validation and duplicate rule. Each new ReadingList evaluates its own array initializer. Returning a copied list prevents callers from editing the internal array through this API. There is no claim that this design persists data between page loads.
Practice quiz
What does this complete program print? class Item { label() { return "item"; } } const a = new Item(), b = new Item(); console.log(a.label === b.label); console.log(Object.hasOwn(a, "label"));
- true false
- true true
- false true
- false false
Answer: true false. Public class methods live on the shared prototype, not as own properties of each instance.
What does this complete program print? const defaults = { color: "blue" }; const item = Object.create(defaults); item.color = "red"; console.log(item.color, defaults.color);
- red red
- red blue
- blue blue
- blue red
Answer: red blue. For this writable data property, assignment creates an own shadowing property.
What does this complete program print? const defaults = { color: "blue" }; const item = Object.create(defaults); item.color = "red"; delete item.color; console.log(item.color);
- red
- undefined
- blue
- null
Answer: blue. Deleting the own property reveals the inherited value.
What does this complete program print? class List { items = []; } const a = new List(), b = new List(); a.items.push("A"); console.log(a.items.length, b.items.length);
- 1 1
- 0 0
- 0 1
- 1 0
Answer: 1 0. The field initializer creates a fresh array during each instance construction.
What does this complete program print? class Item { static label() { return "type"; } } const item = new Item(); console.log(Item.label()); console.log(typeof item.label);
- type undefined
- type function
- undefined function
- type type
Answer: type undefined. A static method is stored on the class object, not on its instances.
What does this complete program print? class Base {} class Child extends Base {} const item = new Child(); console.log(item instanceof Child, item instanceof Base);
- true false
- true true
- false true
- false false
Answer: true true. The instance’s prototype chain includes both Child.prototype and Base.prototype.
What does this complete program print? class Item { #value = 3; read() { return this.#value; } } const item = new Item(); console.log(item.read()); console.log(item["#value"]);
- 3 3
- undefined 3
- 3 undefined
- 3 null
Answer: 3 undefined. The private field is not a public string-keyed property named #value.
What does this complete program print? class Item {} const item = new Item(); console.log(Object.getPrototypeOf(item) === Item.prototype);
- false
- undefined
- TypeError
- true
Answer: true. Ordinary class construction sets the instance’s prototype link to the class prototype.
Continue this course
- Previous: Closures and Scope
- Next: Design Patterns — Apply classic patterns like Module, Observer, and Factory in JavaScript
- Quick reference: JavaScript cheat sheet