how to do oop in javascript

Object-Oriented Programming (OOP) in Javascript can be achieved through the use of classes, inheritance, and encapsulation.

Classes

Classes in Javascript are declared using the class keyword. A class is a blueprint for creating objects with specific properties and methods.

index.tsx
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  getArea() {
    return this.height * this.width;
  }
}
163 chars
11 lines

In the example above, a Rectangle class is defined with a constructor method that takes in a height and width parameter, and two properties height and width. The getArea method calculates and returns the area of the rectangle.

Inheritance

Inheritance in Javascript allows a subclass to inherit properties and methods from a superclass. This is achieved with the extends keyword.

index.tsx
class Square extends Rectangle {
  constructor(sideLength) {
    super(sideLength, sideLength);
  }
  
  setLength(newLength) {
    this.height = newLength;
    this.width = newLength;
  }
}
191 chars
11 lines

In this example, the Square class is created by extending the Rectangle class. The setLength method is added to the Square class to update the length of the sides of the square.

Encapsulation

Encapsulation in Javascript involves hiding internal implementation details of an object and only exposing the necessary properties and methods to the outside world.

index.tsx
class Person {
  constructor(name, age) {
    let _name = name;
    let _age = age;
  
    this.getName = () => _name;
    this.getAge = () => _age;
  }
}

const person = new Person("John", 30);
console.log(person.getName()); // "John"
console.log(person._name); // undefined
276 chars
14 lines

In this example, a Person class is defined with private properties _name and _age that can only be accessed through the getName and getAge methods. The outside world cannot access the private properties directly.

gistlibby LogSnag