Class Syntax
ES6 introduced the class keyword as syntactic sugar over prototype-based inheritance.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
return "Hi, I'm " + this.name + " and I'm " + this.age;
}
}
const alice = new Person("Alice", 30);
console.log(alice.introduce());
Try it Yourself โ
Getters & Setters
Use get and set to define computed properties with accessor syntax.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
set dimensions({ w, h }) {
this.width = w;
this.height = h;
}
}
const rect = new Rectangle(5, 10);
console.log(rect.area);
rect.dimensions = { w: 3, h: 7 };
console.log(rect.area);
Try it Yourself โ
Static Methods
Static methods belong to the class itself, not instances. Use the static keyword.
class MathHelper {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(MathHelper.add(5, 3));
console.log(MathHelper.multiply(4, 2));
Try it Yourself โ