DEV Community

Cover image for Object Oriented Programming (OOP) in JavaScript
Brandon Damue
Brandon Damue

Posted on

Object Oriented Programming (OOP) in JavaScript

This article is a beginner friendly introduction to Object-oriented Programming in JavaScript. In the wake of making it as beginner friendly as possible, we are going to learn what OOP is all about by using real world examples and metaphors so let's begin.

What is OOP?

According to Wikipedia, OOP is a programming paradigm that is based on the concept of objects. What this means is that is OOP is all about modelling or depicting software programs as being made up of a collection of real world entities or objects. A car for instance is a good example of an object in the real world and a car has noticeable properties like tyres, doors, windows and so on. A car also has certain actions(behaviours) that it carries out such as moving, the horn honking, and so on. In Object Oriented Programming, programs are made up of a variety of objects that interact with each other. These objects like real world objects are made up of attributes(properties) and behaviours(methods) and are usually created from a class. You are probably wondering what a class is in OOP. Do not be afraid cause that's what we are diving into right now.

Building Blocks of OOP

Classes

A class is essentially a user defined blueprint or template from which objects are created. It represents the properties and behaviours(methods) common to objects of a specific type. Let's look at this from the perspective of the real world using our sweet ol' car example. Suppose you own a private parking lot where people pay to park their car for a specific duration of time and you want to represent these cars programmatically so that you can run your business more efficiently, creating an object for each will be tedious and redundant cause you will have to repeat code common to all cars each time you can want to create a new car object. A class solves this issue of having to repeat code by providing a template that can be used and reused to create as many car objects as needed. Objects created from a particular class are called instances of that class. Let's see how we will represent our Car class in code;

class Car {
    constructor(make, model, year, dateBroughtIn) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.dateBroughtIn = dateBroughtIn;
    }

    getDaysSpent() {
        //Getter
        return this.calcDaysSpent();
    }

    calcDaysSpent() {
        //calculate the duration for which the car has been parked
        return Date.now() - this.dateBroughtIn;
    }
}
Enter fullscreen mode Exit fullscreen mode

The generic Car class we have created above can then be used to create different car objects and even subclasses.

Objects

Objects are instances of a class. They represent real world entities. An object consist of the following components; state(its properties), behaviour(its methods) and identity. From the Car class we created earlier, let us create an instance of that class.

const car1 = new Car("Tesla", "S", "2017", "5/2/2022");
Enter fullscreen mode Exit fullscreen mode

When the Car class is called with the new keyword, a new object is created and the constructor function is called and it assigns values to its parameters. Something that is worth noting which we haven't talked about yet is that objects must not be created from classes they can also be created by simply using object literals {} as shown in the code below.

const cat = {
            name: "Evaristus",
            color: "Fawn",
            age: 2
            }
Enter fullscreen mode Exit fullscreen mode

Attributes

These are the values associated with a javascript object. They are defined in the class template and receive a value when the class is instantiated. The state of an object is defined by the data contained in its attribute fields.

Methods

Methods are basically behaviours of the object and they perform actions on the object. They might return information about an object, update or even delete an objects data. They are basically functions. A method's code is written within a class definition and then the method is called as needed in instances of that class. One good about methods is that its one of the things that help programmers promote code reusability.

The Four Pillars(Principles) of OOP

OOP is rooted on the following pillars or principles;

  • Inheritance
  • Encapsulation
  • Abstraction
  • Polymorphism We are going to look at each of these principles in small detail so as to gain a clear understanding of what they are all about.

Inheritance

Just as inheritance occurs in real life where children for the most part inherit properties and sometimes behaviours from their parents, inheritance also occurs in OOP where subclasses inherit properties and methods from a parent class. Inheritance is also known as prototyping in JavaScript. The class that is inherited from is called the base or parent class while the class that inherits from the parent class is called the derived or extended class. Inheritance promotes code reusability. From the generic Car class we created earlier we can create more specific subclasses, we can create a subclass for cars that use fuel and another subclass for cars that are electric. Let's see a code example.

// This class inherits properties and methods from the Car class
class ElectricCar extends Car {
       constructor(make, model, year, dateBroughtIn) {
            super(make);
            super(model);
            super(year);
            super(dateBroughtIn);
       }
      electric() {
        console.log('This is an electric car!!!');
       }
}
Enter fullscreen mode Exit fullscreen mode

Encapsulation

Encapsulations means containing or hiding important data within objects and only showing selected data(data that you want to show) to the world. You can visualise encapsulation as a protective shield that protects the code and data behind the shield. In encapsulation, variables or data is hidden and only made accessible to methods that are members of this class. In encapsulation, data in a class is hidden from other classes by making some variables private and this is achieved by declaring fields as private. So encapsulation requires defining some keys as private and others as public.

  • Private methods and properties can be accessed by other methods of the same class. So private methods can only be accessed in the class in which they are defined.
  • Public methods and properties are accessible also from outside the class. What encapsulation does is that it adds security to your program. We can also label methods and properties as Protected which makes them accessible to the class it is defined in as well as subclasses derived from the base class in which the protected property or method is defined.

Note: JavaScript has private and protected properties and methods. Protected Fields are prefixed with a _ while private fields are prefixed with a #. Protected fields are inherited, private ones aren’t.

Encapsulation makes collaborating with other developers easier since you can easily hide properties and methods that you don't want other developers to tamper with as being private. Other benefits of encapsulation are outlined below.

  • It adds security since only public properties and methods can be accessed from outside the class.
  • It helps protect against common mistakes since only public methods and properties are accessible, developers can't accidentally change something sensitive.
  • It helps hide complexity by only displaying information that has to be seen. ## Abstraction Abstraction means hiding complexity and allowing the user to interact only with selected properties and methods of an object. For example to drive a car, you need not know how the engine works all you have to know is how to use the steering wheel, gas and brake pedals, blinkers and so on. All the engineering that determines how the car functions under the hood is hidden to the driver. Abstraction is an extension of encapsulation. Some of the benefits of abstraction are highlighted below;
  • Adds security
  • Hides complexity
  • Provides easier software maintenance.

Polymorphism

To have a clear understanding of what polymorphism is, let's look at what the word means in itself. Polymorphism is a Greek word which means having many forms or many shapes. In simpler terms, we can describe it as the ability of a message to be displayed in more than one form. Let's look at a real-life example a man can perform many roles concurrently; he can be a father, a husband and an employee. So the same person is performing different roles in different situations. This is polymorphism. It is considered the third pillar of OOP after inheritance and encapsulation. Polymorphism allows us to perform a single action in different ways. What this really means is that polymorphism allows you to define one interface and have multiple implementations. Polymorphism allows the same method to execute different behaviours in two ways: method overriding and method overloading.

Method Overriding

Method Overriding occurs when a derived or extended class has a definition for one of the member functions (methods) of the base class. That base function is said to be overridden. Method overriding is used in Runtime polymorphism.

Method Overloading

When there are multiple functions with the same name but different parameters, they are said to be overloaded. Compile Time polymorphism uses method overloading. Different results may occur depending on the number of parameters passed in. Some of the benefits of polymorphisms;

  • Method overloading
  • Method overriding
  • Objects of different types can be passed through the same interface.

Before we conclude, let's look at some of the benefits of OOP.

  • Object-oriented programs are easier to debug, classes often contain all applicable information to them.
  • Reusability - OOP objects can be used across programs.
  • OOP models complex things as reproducible, simple structures
  • OOP promotes security by protecting data through encapsulation.
  • It allows for class-specific behaviour through polymorphism.

Conclusion

Learning about the inner workings of OOP like most concepts in programming can seem difficult in the beginning but when you get a grip of these concepts, everything begins to add up. Thank you for reading this article.

Top comments (0)