Classes, Prototypes and Inheritance
How prototypes work, ES classes, constructors, getters and setters, private fields, inheritance and when to prefer composition.
JavaScript Objects Can Share Behavior Through Prototypes
An object stores properties and can delegate a property lookup to another object called its prototype. If a property is not found directly, JavaScript checks the prototype, then that object's prototype, continuing up the chain until it finds the property or reaches the end. This delegation lets many objects share methods without copying a method onto every instance.
const vehicleBehavior = {
describe() {
return this.name + ' is ready'
},
}
const scooter = Object.create(vehicleBehavior)
scooter.name = 'City scooter'
console.log(scooter.describe())
console.log(Object.getPrototypeOf(scooter) === vehicleBehavior)The method is owned by vehicleBehavior, while name belongs to scooter. During the method call, this is still the object before the dot. Most application code uses object literals and classes, but understanding delegation explains how shared methods and built-in APIs work.
Own Properties and Inherited Properties Are Different
Object.hasOwn() checks whether an object itself contains a property. The in operator also checks its prototype chain. This distinction matters when enumerating data, copying records, or deciding whether a property is inherited behavior. Avoid creating prototypes from untrusted input or changing built-in prototypes.
const sharedActions = {
open() {
return 'Opening ' + this.label
},
}
const panel = Object.create(sharedActions)
panel.label = 'course panel'
console.log(Object.hasOwn(panel, 'label')) // true
console.log(Object.hasOwn(panel, 'open')) // false
console.log('open' in panel) // true
console.log(panel.open())Property lookup follows the chain at runtime. If a property is assigned directly to an instance, it can shadow an inherited property with the same name. That flexibility is powerful, but it can also make behavior harder to trace when objects are modified without a clear contract.
| Question | Useful check | What it includes |
|---|---|---|
| Does this object own the property? | Object.hasOwn(object, key) | Only direct properties |
| Can this object access the property? | key in object | Direct and inherited properties |
| What object is its prototype? | Object.getPrototypeOf(object) | The next link in the delegation chain |
Use a Class to Create Similar Objects
A class gives you a named pattern for constructing instances. The constructor initializes each instance; methods are placed on the class prototype and shared. Calling a class without new throws. Use classes when the application benefits from a clear type of object with related state and behavior, not just because a record has several fields.
class CourseProgress {
constructor(title, completedLessons = 0) {
this.title = title
this.completedLessons = completedLessons
}
completeLesson() {
this.completedLessons += 1
return this.completedLessons
}
}
const javascript = new CourseProgress('JavaScript')
javascript.completeLesson()
console.log(javascript.title, javascript.completedLessons)
console.log(Object.hasOwn(javascript, 'completeLesson')) // falseThe instance has its own fields; the method is shared through the prototype. Class bodies run in strict mode, so a detached method has no implicit global receiver. If a method is passed somewhere else, preserve the receiver intentionally rather than assuming the class binds it automatically.
Getters, Setters and Private Fields
A getter computes a property when it is read, and a setter can validate a value when it is assigned. Use them when they make an object's public interface clearer, not to disguise expensive or surprising work as a simple property read. Private fields use a # prefix and can only be accessed inside the class body. They are useful for enforcing an invariant but are not a replacement for validation at external boundaries.
class QuizScore {
#points = 0
get points() {
return this.#points
}
add(points) {
if (!Number.isFinite(points) || points < 0) {
throw new Error('Points must be a non-negative number')
}
this.#points += points
}
}
const score = new QuizScore()
score.add(8)
console.log(score.points)
// score.#points is not accessible outside the classThe example keeps the internal field private and exposes only the operations the caller needs. Returning a copy of mutable internal collections can also prevent callers from bypassing the class's rules. Keep the public API small so future changes do not break every caller.
Inheritance Reuses Behavior but Adds Coupling
A subclass extends a base class and can add behavior. Its constructor must call super() before using this. Inheritance works best for a genuine "is a" relationship with a stable shared contract. A deep hierarchy makes changes ripple across multiple levels, so keep it shallow and prefer composition when an object can use a capability without being a subtype.
class LearningResource {
constructor(title) {
this.title = title
}
summary() {
return this.title
}
}
class VideoLesson extends LearningResource {
constructor(title, durationMinutes) {
super(title)
this.durationMinutes = durationMinutes
}
summary() {
return super.summary() + ' (' + this.durationMinutes + ' min)'
}
}
const lesson = new VideoLesson('Closures', 14)
console.log(lesson.summary())Overriding a method should preserve the expectations callers have about the base behavior. If a subclass cannot be used wherever the base type is expected, the relationship may be misleading. A small focused object passed into a larger object often makes the intended collaboration clearer.
Build Objects from Capabilities When That Is Simpler
Composition means combining smaller objects or functions to create a behavior, instead of creating a subclass for every variation. A course can receive a formatter or storage adapter as a dependency. This keeps policy separate from the object that uses it and makes behavior easier to replace in tests.
function createCourseCard(course, formatDuration) {
return {
title: course.title,
durationLabel: formatDuration(course.minutes),
}
}
const formatMinutes = (minutes) => minutes + ' min'
const card = createCourseCard(
{ title: 'Array methods', minutes: 35 },
formatMinutes
)
console.log(card)- Start with the behavior callers need, not with a hierarchy diagram.
- Use a class when instances share state and a stable set of operations.
- Use inheritance for a true subtype with a substitutable contract.
- Use composition when behavior is a replaceable capability or policy.
- Keep constructors and methods small, and test public behavior through the interface.
Plain objects and functions are often enough. Classes are a tool, not a requirement for object-oriented design. Pick the simplest representation that preserves the rules the application needs.
Common Mistakes
Assuming a method is copied onto every instance
Why: Class methods are shared through the prototype unless defined as instance fields.
Fix: Use Object.hasOwn and Object.getPrototypeOf when inspecting where behavior lives.
Calling a class without new
Why: Class constructors are designed to create instances and reject ordinary function calls.
Fix: Create instances with new or use a factory function when construction syntax is not useful.
Using this before super() in a subclass constructor
Why: A derived instance is not initialized until the base constructor runs.
Fix: Call super() first, then set subclass fields.
Building a deep inheritance tree for every variation
Why: Each layer couples behavior and makes overrides difficult to reason about.
Fix: Prefer shallow hierarchies or compose small capabilities as dependencies.
Model a Small Learning Catalogue
Practice
Use prototypes, classes and composition deliberately
- Create two objects that delegate a shared describe method through Object.create, and check own versus inherited properties.
- Write a CourseProgress class with a private completed count, a getter, and a method that validates completion updates.
- Create a VideoLesson subclass and call an overridden summary method that uses super.
- Refactor one optional behavior into a function dependency passed to a factory instead of another subclass.
- Write tests using plain assertions for valid updates, invalid inputs, and the public output of each object.
Hint: Test behavior through public methods. Avoid exposing private state only to make a test pass.
🎯 Key Takeaways
- ✓Objects delegate property lookup through a prototype chain.
- ✓Object.hasOwn checks direct data; the in operator includes inherited properties.
- ✓Class syntax builds instances whose methods are generally shared on the class prototype.
- ✓Getters, setters, and private fields can protect a small public interface and internal invariants.
- ✓Inheritance models a true subtype and must preserve the base contract.
- ✓Composition is often clearer when behavior is a replaceable capability rather than an identity relationship.
Next
What comes next
Connect JavaScript behavior to browser elements and respond to user interactions.
Lesson 06 · The DOM and Events →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
