Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

JavaScript Classes and Inheritance

Learn object-oriented programming in JavaScript using classes.

jiocoder TeamUpdated Jun 6, 20261 min readJavaScript
JavaScript Classes and Inheritance

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;
    }
  }
}

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment