Classes
A class is a template to create objects of the same type. It defines what
data they will have (in the constructor) and what they can do (the methods).
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const ana = new Person("Ana", 30);
console.log(ana.greet()); // "Hi, I'm Ana"
constructor: special method that runs when the object is created withnew. It is used to initialize the properties.new Person(...): creates a new instance of the class.- Methods are written inside the class, without the
functionkeyword.
Prototypes: what lies underneath
Classes are a more convenient syntax over JavaScript's prototype system.
Methods are not copied into each object: they live in a shared object (the
prototype) and every instance consults it. That is why creating a
thousand people does not duplicate the greet method a thousand times.
Examples
Defining a class and creating instances
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const r = new Rectangle(4, 3);
console.log("Area:", r.area());