Free Handbook · Runs in your browser

Objects, Prototypes & Classes

Objects as records with methods and this; the prototype chain that every object is built on, traced; class syntax with constructors, inheritance and super; getters, setters, static and private fields; and when composition beats inheritance.

0 / 111 lessons🔥 0 day streak
ShareXLinkedIn

Module 08 · what you'll be able to do

  • Explain what the prototype chain is and how property lookup walks it
  • Write classes with constructors, methods, inheritance and super
  • Use getters, setters, static members and #private fields
  • Know the two class errors: calling without new, and this before super
  • Choose composition over inheritance and know why
01

Objects with methods

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
Ada: 120 Ada: 120
5 10 false

That last false is the motivation for everything that follows: a factory copies every method into every object. With a thousand accounts that is a thousand copies of deposit. Prototypes let objects share one copy.

02

The prototype chain

Every object has a hidden link to another object, its prototype. When you read obj.x and obj has no own property x, the engine looks at the prototype, then the prototype's prototype, until it reaches null. That is the whole mechanism behind methods, inheritance and classes: [].push is not on your array, it is on Array.prototype, one object shared by every array ever made.

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
Rex has 4 legs
true false true
true
3 4
true true null
false function
10 0 true true true
VisualizeLooking up dog.describe()Step 1 / 5
const animal = { legs: 4, describe() { return this.name + " " + this.legs } }
const dog = Object.create(animal)
dog.name = "Rex"
console.log(dog.describe())
Line 2

Create an empty object whose prototype link points at animal.

Variables now
dog{} → animal
All 5 steps as a table
StepLineWhat happenedVariables now
12Create an empty object whose prototype link points at animal.dog = {} → animal
23Set an own property on dog.dog = { name: "Rex" } → animal
34Look up describe on dog. Not an own property.
44Follow the prototype link to animal. Found describe there.
54Call it with this = dog (rule 1: the object before the dot). Inside, this.name is own ("Rex"); this.legs is not own — walk to animal again → 4.
Why it matters even if you only write classes
Every "why is this wrong", every "method is not a function", every monkey-patch like Array.prototype.last = …, and every framework's magic is the prototype chain. Ten minutes here saves hours later.
03

Classes

class is the readable syntax for the constructor-plus-prototype pattern above: the constructor sets up own properties, methods go on the prototype automatically, and new wires them together. It is not a new object model — it is the same one with better spelling and strict mode built in.

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
Ada: 175 2
true false function
function Account
RangeError deposit must be positive
false true
Your turn
Add a withdraw(amount) method that throws if funds are insufficient, and a history() method that returns the transactions as strings like "deposit 50".
Error you will hit

TypeError: Class constructor Account cannot be invoked without 'new'

javascript
class Account { constructor(o) { this.owner = o } }
const a = Account("Ada")
Uncaught TypeError: Class constructor Account cannot be invoked without 'new'
    at your code:2
Why the engine said that

A class must be called with new, which creates the object, sets its prototype and binds this. Old-style constructor functions silently ran as plain functions when you forgot; classes refuse.

The fix

new Account("Ada"). If you want a call without new, expose a static factory: static create(o) { return new Account(o) }.

04

Inheritance and super

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
circle with area 3.14
square with area 4.00 (four equal sides)
blob with area 0.00
true true true
true
3 3 true
auto
Error you will hit

ReferenceError: Must call super constructor in derived class before accessing 'this'

javascript
class Shape { constructor(n) { this.name = n } }
class Circle extends Shape {
  constructor(r) {
    this.r = r          // before super()
    super("circle")
  }
}
new Circle(1)
Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
    at new Circle (your code:4)
Why the engine said that

In a derived class, this does not exist until the parent constructor has created it. super(...) is the call that creates it.

The fix

Call super() first, then set your own fields. If the class has no constructor at all, one is generated that does this for you.

javascript
class Circle extends Shape {
  constructor(r) {
    super("circle")
    this.r = r
  }
}
Quick check

Where does a method defined in a class body live?

05

Getters, setters, static and #private

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
25 77 25°C
100
below absolute zero
0°C 2 -273.15
true false []
Your turn
Write a Counter class with a private #n, increment(), a getter value, and a static total that counts every increment across all counters.
When to use each
Getter: a computed value that reads like a property (user.fullName). Setter: validation on assignment. Static: belongs to the class, not an instance — factories, counters, constants. #private: real privacy, enforced by the engine — not the _underscore convention. #x in obj (checking for a private field) is valid only inside the class body; outside it is a SyntaxError.
06

Composition, mixins and making a class iterable

Inheritance says "a Square is a Shape". It works for one or two levels and then becomes a tangle — the classic "Dog extends Animal extends LivingThing" hierarchies nobody can change. Composition says "a Car has an Engine": build objects from smaller objects and functions. It is more flexible, easier to test, and what most modern JavaScript (and React) does. Reserve extends for genuine specialisation — errors, framework base classes.

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
Donald flies | Donald swims
[api] ok
[ 1, 2, 3, 4, 5 ] 5
odd 1
odd 3
odd 5
1 2
[ 'plain object', 'instance' ]
Mid-levelHow does inheritance work in JavaScript, and how is it different from Java or Python?

JavaScript uses prototypal inheritance: objects link to other objects, and property lookup walks that chain. class is syntax over it — methods go on Class.prototype, extends links prototypes. There are no true classes as blueprints separate from objects, no interfaces or abstract classes at runtime, single inheritance only (mixins via Object.assign for more), and you can change a prototype after objects exist. The practical difference: composition and plain objects are idiomatic here.

SeniorWhen would you choose a class over closures / plain objects, and vice versa?

A class when there are many instances sharing behaviour (memory: one method copy), when identity and instanceof matter (custom errors, domain entities), or when a framework expects one. Closures and plain objects when there is one instance (a module, a service), when you want real privacy without #, or when the thing is data rather than behaviour. Both are fine; consistency within a codebase matters more than the choice.

Finish the JavaScript handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.