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.
class Animal {
constructor(name) { this.name = name; }
speak() { return this.name + " makes a sound"; }
}
let a = new Animal("Cat");
console.log(a.speak());Cat makes a soundnew Animal('Cat') creates an instance, running the constructor.
class Dog extends Animal {
speak() { return this.name + " barks"; }
}
let d = new Dog("Rex");
console.log(d.speak());Rex barksDog 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.
