JavaScript ยท Chapter 45 of 55

JavaScript Classes

Classes are syntactic sugar over JavaScript's prototype-based inheritance, providing a cleaner, more familiar way to create objects and share behaviour through methods.

A class defines a `constructor` method for initialization and other methods that instances can call. The `extends` keyword enables inheritance between classes.

Defining a class

`class Animal { constructor(name) { this.name = name; } speak() { return this.name + ' makes a sound'; } }` defines a reusable blueprint for objects.

Inheritance with extends

`class Dog extends Animal { speak() { return this.name + ' barks'; } }` lets Dog reuse and override Animal's behaviour, and call `super()` to access parent logic.

Example 1 (javascript)
class Animal {
  constructor(name) { this.name = name; }
  speak() { return this.name + " makes a sound"; }
}
let a = new Animal("Cat");
console.log(a.speak());
Output
Cat makes a sound

new Animal('Cat') creates an instance, running the constructor.

Example 2 (javascript)
class Dog extends Animal {
  speak() { return this.name + " barks"; }
}
let d = new Dog("Rex");
console.log(d.speak());
Output
Rex barks

Dog inherits from Animal but overrides the speak method.

Key points

  • Classes are templates for creating objects with shared behaviour.
  • The constructor method initializes new instances.
  • extends enables inheritance; super() calls the parent constructor/methods.
  • Classes are syntactic sugar over prototype-based inheritance.
๐Ÿ’ก Note: Under the hood, class methods live on the prototype, so all instances share the same method code efficiently.

๐Ÿ“ Quick Quiz

1. Which keyword creates a new instance of a class?

2. Which keyword enables class inheritance?

3. What does the constructor method do?