Prototypes and classes
Every JavaScript object has a hidden link to another object called its prototype, and that is where shared methods like toString live. Classes are syntactic sugar over this same prototype system, so understanding prototypes explains how class, extends and super really work.
12.1 The problem: a method copy in every object
- A factory function that returns { name, greet() {} } creates a new greet function on every call.
- 10,000 users means 10,000 copies of the same logic: memory wasted.
- Only the data (name) differs; the method should live in one shared place: the prototype.
function createUser(name) { return { name, greet() { return `Hi, I am ${this.name}`; }, };} const a = createUser("Rahul");const b = createUser("Priya");console.log(a.greet());console.log(a.greet === b.greet);Hi, I am Rahulfalse12.2 The hidden link: prototype
- { name: "Rahul" } has no toString of its own, yet user.toString() works.
- Object.hasOwn(user, "toString") is false: it is not an own property.
- Object.getPrototypeOf(user) === Object.prototype, and toString is defined there.
const user = { name: "Rahul" }; console.log(user.toString());console.log(Object.hasOwn(user, "toString")); const proto = Object.getPrototypeOf(user);console.log(proto === Object.prototype);[object Object]falsetrue12.3 How the prototype chain works
- Step 1
1.Access user.toString
- Step 2
2.Look in the object itself -> found? use it
- Step 3
3.Not found -> follow the hidden link to the prototype
- Step 4
4.Search that prototype, then its prototype (Object.prototype)
- Step 5
5.Chain ends at null -> still not found = undefined
Reads walk up the chain; writes always go on the object itself
12.4 Fix: put the method on the prototype
- Write greet once in a userMethods object.
- Object.create(userMethods) makes an empty object whose prototype is userMethods.
- this still points to the calling object, so each prints its own name.
- a.greet === b.greet is now true: one shared function.
const userMethods = { greet() { return `Hi, I am ${this.name}`; },}; const a = Object.create(userMethods);a.name = "Rahul";const b = Object.create(userMethods);b.name = "Priya"; console.log(a.greet());console.log(b.greet());console.log(a.greet === b.greet);Hi, I am RahulHi, I am Priyatrue12.5 The same thing with a class
- constructor sets the initial data of the new object.
- Methods written in the class body go on User.prototype (shared).
- new creates the object, sets the prototype link and runs the constructor automatically.
class User { constructor(name) { this.name = name; } greet() { return `Hi, I am ${this.name}`; }} const a = new User("Rahul");const b = new User("Priya");console.log(a.greet());console.log(a.greet === b.greet);Hi, I am Rahultrue- Step 1
1.Create a new empty object
- Step 2
2.Link its prototype to User.prototype
- Step 3
3.Run constructor with this = the new object (this.name = "Rahul")
- Step 4
4.Return the object
- Step 5
5.a.greet() -> not on a -> found on User.prototype
12.6 Checkpoint: a class is a function
class User { greet() { return "Hi"; }} console.log(typeof User);const proto = User.prototype;console.log(Object.hasOwn(proto, "greet"));functiontrue- typeof User is function: a class is a special function.
- greet is an own property of User.prototype, which is why a class is called syntactic sugar over prototypes.
12.7 Inheritance: extends and super
- extends links Admin.prototype to User.prototype, so Admin objects get all User methods.
- super(name) runs the parent constructor; only after it can you use this.
- super.greet() calls the parent's version of a method you are overriding.
class User { constructor(name) { this.name = name; } greet() { return `Hi, I am ${this.name}`; }}class Admin extends User { constructor(name, role) { super(name); this.role = role; } greet() { return `${super.greet()} (${this.role})`; }}const admin = new Admin("Neha", "owner");console.log(admin.greet());Hi, I am Neha (owner)12.8 Private fields
- A field starting with # (#balance) can only be accessed inside the class.
- Methods can validate changes (add rejects amount <= 0); a getter allows read-only access.
- Private fields do not show in Object.keys and accessing w.#balance outside is a SyntaxError.
- This is the class version of the private state built with closures.
class Wallet { #balance = 0; add(amount) { if (amount <= 0) return; this.#balance += amount; } get balance() { return this.#balance; }}const w = new Wallet();w.add(500);console.log(w.balance, Object.keys(w));500 [] // w.#balance outside the class:SyntaxError: Private field '#balance' must be declared in an enclosing class12.9 Comparison: factory vs Object.create vs class
| Point | Factory returning object | Object.create(proto) | class + new |
|---|---|---|---|
| Methods | Copied into every object | Shared on the prototype | Shared on Class.prototype |
| a.greet === b.greet | false | true | true |
| Setup | Simple | Manual: create, then set fields | constructor does it |
| Inheritance | Manual | Manual chaining | extends + super |
| Private data | Closures | Closures | #private fields |
12.10 Common mistakes
- Using this before super() in a child constructor: ReferenceError, because the parent constructor creates the object. Call super first.
- Thinking JS classes copy methods into every object like Java / C#: methods live once on the prototype; objects hold only their data.
- Adding your own methods to built-in prototypes like Array.prototype or Object.prototype.
- Using extends without a real is-a relation (an Admin is a User; a Cart is not a User).
// Wrong: ReferenceErrorclass Admin extends User { constructor(name, role) { this.role = role; super(name); }} // Right: super firstclass Admin extends User { constructor(name, role) { super(name); this.role = role; }}12.11 Interview tips
- Every object has a hidden link ([[Prototype]]) to its prototype; Object.getPrototypeOf reads it.
- Missing properties are searched up the prototype chain, which ends at null (result undefined).
- class is syntactic sugar: typeof Class is function and methods sit on Class.prototype.
- In a subclass, call super() before touching this.
- #private fields give true privacy; closures were the older way.