Classes: Syntax & Inheritance

Organize your code using object-oriented blueprints. Learn how to construct instances and share logic using ES6 class syntax.

JavaScript8 min readConcept 23 of 62

What is a Class?

A class in JavaScript is a blueprint for creating objects. Introduced in ES6, it provides a much cleaner, more familiar syntax for object-oriented programming compared to older prototype-based constructor functions.

A class groups related data (properties) and behavior (methods) together into a single, reusable template.

The Constructor and 'new'

Every class has a special constructor() method. This function runs automatically whenever you create a new instance of the class.

To create an instance, you must use the new keyword, like const hero = new Player('Link'). The new keyword creates a fresh object, binds this to that new object, and returns it.

Inheritance (extends & super)

You can create a new class based on an existing one using the extends keyword. For example, class Warrior extends Player.

The child class inherits all methods from the parent. However, if the child class has its own constructor, it MUST call super() before it is allowed to use the this keyword. super() executes the parent's constructor first.

The Class Factory

Step through the code to see how the new keyword builds an instance, and how extends and super link a subclass to its parent.

The Class Factory

// 1. Parent Class
class Player {
constructor(name) {
this.name = name;
}
}
// 2. Child Class (Inherits)
class Warrior extends Player {
constructor(name, weapon) {
super(name); // Must call first!
this.weapon = weapon;
}
}
// 3. Instantiation
const p = new Warrior("Link", "Sword");
Construction Memory
Click Start to execute new Warrior(...)
iA class requires the new keyword to construct an instance.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if a child class with a constructor forgets to call `super()`?
  2. 2What does the `new` keyword do?
  3. 3Are JavaScript classes exactly the same as classes in languages like Java or C++?

Remember this

  • A class is a blueprint for creating objects.
  • The constructor() runs automatically when you use the new keyword.
  • The new keyword creates the object and binds this.
  • extends creates a subclass that inherits from a parent.
  • You must call super() in a subclass constructor before accessing this.

Done with this concept?

Mark it complete to track your progress. No login needed.