JavaScript Classes and Inheritance
Learn object-oriented programming in JavaScript using classes.

Class Syntax#
Code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
static createAnonymous() {
return new Person('Anonymous', 0);
}
}
const person = new Person('John', 30);
person.greet(); // "Hello, I'm John"Inheritance#
Code
class Student extends Person {
constructor(name, age, school) {
super(name, age);
this.school = school;
}
study() {
return `${this.name} is studying at ${this.school}`;
}
}
const student = new Student('Jane', 20, 'MIT');
student.greet(); // Inherited from Person
student.study(); // "Jane is studying at MIT"Getters and Setters#
Code
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
set width(value) {
if (value > 0) {
this._width = value;
}
}
}