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.tsx163 chars11 linesIn 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.tsx191 chars11 linesIn 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.tsx276 chars14 linesIn 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