Lesson 28 / 38
Classes & Constructors
Blueprints for objects, built with the class keyword.
class and constructor
constructor runs automatically when you create an object with new, setting up its initial properties.
class Dog {
constructor(name, age) {
this.name = name;
this.age = age;
}
bark() {
return `${this.name} says Woof!`;
}
}
const rex = new Dog("Rex", 3);
console.log(rex.bark());Classes are syntax sugar
Under the hood, JS classes still use prototypes — class is a cleaner syntax over the same prototype-based system.
The new keyword
Forgetting new before a class constructor throws a TypeError — classes can't be called like regular functions.