Object Oriented Programming In JavaScript.

·

5 min read

Object Oriented Programming In JavaScript.

If you have prior programming knowledge in languages like C#, C++ or Java, you probably would have heard of Object Oriented Programming. If you've not, well, let's break it down.

First, what are Objects?

An Object is a variable that has a number of properties and a property is an association between a key and a value. Below is an example of an object called vendor with its properties. The keys are name, age and height while the values are "Tayo", 27 and "6 feet". The keys can have values which are strings, numbers or functions (which are called Methods).

let vendor = { name: "Tayo", age: 27, height: "6 feet" }`

Object Oriented Programming in JavaScript is a method of writing JavaScript programs using Objects. It has been around for ages and unlike frameworks that come and go, it is here to stay because it is not a tool but a method or style of programming. The idea of OOP is that we use Objects to model something we want to represent in our program and the kind of functionalities we want it to have.

One of the common ways we write JavaScript programs is by the use of functions, i.e. we define and store data inside the function and the function carries out whatever action we want to take. This is called a procedural way of programming.

The downside of this way of writing programs is that as our application grows, it becomes more difficult to manage several functions interconnected to each other and we might run into spaghetti code. Object Oriented Programming solves this.

There Are Four Concepts of Object Oriented Programming in JavaScript.

1. Encapsulation

In OOP, we store related functions and variables in an Object. This clean way of storing Object data is called Encapsulation. Below is an example showing you how this works.

//using functions to calculate BMI
let weight = 60
let height = 1.72
function calcBmi(weight, height){
 return weight/(height**2);
}
//to invoke this function, we say calcBmi(weight,height);

//using OOP to calculate BMI
let person = {
        weight: 60,
       height:  1.72,
       calcBmi: function(){
                    return this.weight/(this.height**2)
                    }}
//to invoke this function we say person.calcBmi()

From the code written above, we can see that we don't need to pass in parameters to invoke the calcBmi function in OOP. We use the dot notation. i.e person.calcBmi(). Whereas, when we use functions, we have to pass in more parameters.

The best functions are those with no parameters -Robert C martin

2. Abstraction

An Object can have several different properties but we can decide to only display the properties we need. This is known as ABSTRACTION. According to Mozilla Developer Network , Abstraction means creating a simple model of a more complex thing, which represents its most important aspects in a way that is easy to work with for our program's purposes.

New Objects can be created from a parent Object which are called classes, this process is called Instantiation and a function called the constructor function is used to create it.

/* Food is a constructor function because we create an instance of an 
 empty object. To invoke a new Object, we use the "new" keyword.*/

function Food (typeOfFood) {} 

/* ricePudding is a new Object created by the constructor function "Food".*/

let ricePudding= new Food ("rice);

3. Inheritance

We can also create new classes from the parent class give it the properties of the parent class. This process is called inheritance. The subclass inherits information from the parent class. This new class has all the functionalities of the parent class and new data can also be added which is specific to that class. This prevents us from having to write the same code over and over again.

/*A constructor function creating an instance of an Object 
with its various properties. */

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.intro = function() {
    alert('Hi! I\'m ' + this.name + ' I am ' + this.age + ' years old.');
  };
}

let firstPerson = new Person('Mary', 22);
firstPerson.race = "African"

//console.log(firstPerson) would give an Object below;
{  name: 'mary',
    age: 22,
    race: African,
    intro: function() {
    alert('Hi! I\'m ' + this.name + ' I am ' + this.age + ' years old.');
  };
} 

let secondPerson = new Person('John', 31);
// while the second Object would give;
{
name: 'John',
age: 31,
intro: function() {
    alert('Hi! I\'m ' + this.name + ' I am ' + this.age + ' years old.');
  };

4. Polymorphism

Polymorphism simply means representing something in different forms. I. e  the ability to write a single function, variable, or an object that can handle different data-types . Lets take a look;

/* instance of a parent class. We don't call methods
 inside constructors when we use the 'class' keyword */

lass Animal {
  constructor(name) {
    this.name = name;
  }
  info() {
    console.log(this.name + " can be found in the zoo");
  }
}
let lion = new Animal("Lion");
let lion = new Animal('Lion')

//lion.info() would log "Lion can be found in the zoo" to the console.

/* A new instance of the Animal Object with the method 
having a different property. */

class favAnimal extends Animal {
  info() {
    console.log(this.name + " is my favorite animal");
  }
}


let cat = new favAnimal('cat')

/*cat.info() would log  "Cat is my favourite animal" to the console*/

In the code snippet above, we can see how the "Info" method acts differently in the two object instances. That's the idea of polymorphism. In each Objects, it logs a different string to the console.