O.O.P. in Javascript

JS and OOP

    Programming paradigms used to create JS applications

  • Prototype-Based Programming
  • Object-Oriented Programming
  • Functional-Oriented Programming

Prototype-based approach is "default way" to construct classes BUT DOESN'T support Encapsulation

ES6 classes ES6 classes 2

Prototype Version

Prototype JS exmaple

Polymorhpism

Classes

A class is a template for generating objects during runtime.

classes JS Another way define a class JS

At first sight, it seems to be a better version because it doesn’t require the getter (getName & getPrice) methods anymore and is therefore shorter.

Unfortunately, you have now given full access to the properties from the outside. So everybody could access and modify it...which you don't want because it makes the application more difficult to maintain.

bad class access example JS

Objects should have exclusive control over their data. In other words, the objects “encapsulate” their data and prevent other objects from accessing the data directly. The only way to access the data is indirect via the functions written into the objects.

JS classes example Salesforce

Encapsulation

Encapsulation prevents access to data except through the object’s functions.

Objects should have exclusive control over their data. In other words, the objects “encapsulate” their data and prevent other objects from accessing the data directly. The only way to access the data is indirect via the functions written into the objects.

Inheritance

Inheritance lets you create a new class by extending an existing class with additional properties and functions.

he new class “inherits” all of the features of its parent, avoiding the creation of new code from scratch. Furthermore, any changes made to the parent class will automatically be available to the child class. This makes updates much easier.

inheritance JS

Let’s say we have a new class called Book that has a name, a price and an author. With inheritance, you can say that a Book is the same as a Product but with the additional author property. We say that Product is the superclass of Book and Book is a subclass of Product:

Subclasses can inherit properties and functions from superclasses while adding properties and functions of their own.

Inheritance is a powerful tool for avoiding redundancy