Classes and Objects
Prerequisites: Functions, Objects
ES6 (2015) added class syntax as a cleaner way to write the
constructor-function-plus-prototype pattern JavaScript always had
under the hood. A class groups related data and behavior together; each
object made from it is called an instance.
Syntax
class ClassName {
constructor(...) {
// ...
}
}
Example
class User {
constructor(name, role) {
this.name = name;
this.role = role;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const ada = new User("Ada", "admin");
console.log(ada.greet());
Expected output
Hi, I'm Ada
Unlike Python or PHP, JavaScript classes are still prototype-based
under the hood — class is syntax sugar over that existing system, not
a separate mechanism.
Practice
Write a Rectangle class with width and height, and a method
area() that returns width * height.
Show solution
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const r = new Rectangle(4, 5);
console.log(r.area());