An Introduction to Object Oriented Programming in JavaScript
Tags: webdev, javascript, programming, beginners
Published: 2023-03-25 14:51:12

so what is object-oriented programming? it is a style of programming that is centered around objects .that is a kind of binding or tie that exists between data which are referred to as properties of the object and functions that operates on that data which are called methods in OOP. The combination of member variables (properties of the object) and member functions (methods that operate on the variables) is referred to as an object. OOP breaks down a problem into several entities called objects and these objects can then communicate with each other.

Object Oriented Programming is not a tool or a framework but a programming paradigm. several programming languages support oop such as c#, Java, Ruby, PHP and more. many of the frameworks out there such as laravel, spring boot, and .NET framework were designed using object-oriented principles. if you want to go far in your career as a software developer, you need to understand object-oriented programming principles.

In this article, I'm going to explain object-oriented principles and how to implement them in JavaScript.

## Basic Concepts of Object-oriented Programming

### Objects

An Object is a unique entity that contains properties and methods. if you take a look around you right now, you'll find many examples of real-world objects: your mobile phone, your dog (if you have one)

Real-world objects share two characteristics: They all have states and behavior. Dogs have state (name, color, breed) and behavior (barking, fetching, wagging tail). Software objects are kind of similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (which can also be referred to as variables) and behaviors are expressed through methods (which can also be referred to as functions in some programming languages). Methods operate on an object's internal state. they serve as the channel for object-to-object communication. Hiding the internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation.

The object can be created in two ways using JavaScript

#### Object Literal

#### Example:
 Using Object literal:



```
const Student = {

   // properties

name: "James",

age: 21,

gender: "Male",

Department: "Computer Science",

// method

getDetails: function() {

return `Student Name ${this.name} Student age: ${this.age}

gender: ${this.gender} Department: ${this.Department}`;

     }

}
```

#### Constructor Function

#### Examples: 
using object constructor:

```

function Student(name, age, gender, Department) {

this.name = name;

this.age = age;

this.gender = gender;

this.Department = Department;

this.getDetails = function() { return Student Name ${this.name}, Student age: ${this.age}, gender: ${this.gender}, Department: ${this.Department};
   }

}
```

### Classes

In the real world, you'll often find many individual objects all of the same kind. let's say for example your mobile phone. there may be thousands of other phones in existence, all of the same make and model. Each phone was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your phone is an instance of the class of objects known as a Phone. A class is a blueprint from which individual objects are created. another scenario is that a real estate developer can use a single architectural blueprint to make multiple replicas of the same type of building.

There is something I want you to take note of, unlike other Object Oriented languages there are no classes in JavaScript we have only Object. JavaScript is a prototype-based language, meaning that it doesn't have classes, rather it defines behaviors using a constructor function and then reuses it using the prototype.



> _JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance._
> -Mozilla Developer Network
let's look at the two ways in which one can obtain a class-like behavior in JavaScript.

#### Example 1: Using ES6 Class Syntax


```
// Defining class using ES6

class Vehicle {

constructor(name, model, maker)

{

this.name = name;

this.model = model;

this.maker = maker;

}
 getDetails() {

return The name of the Vehicle is ${this. name}.

}

} // Making object with the help of the constructor let vehicle1 = new Vehicle('corolla', 2010, 'Toyota'); console.log(vehicle1.name); console.log(vehicle1.maker); console.log(vehicle1.model); console.log(vehicle1.getDetails());

```

#### Example 2
: Simulating Classes Using Constructor functions

```
// Defining class using Object Constructor function Vehicle(name, model, maker) {

this.name = name;

this.model = model;

this.maker = maker;

this.getDetails = function() {

console.log('The name of the bike is ' + this.name);

}

}; let vehicle1 = new Vehicle('corolla', 2018, 'Toyota');

vehicle1.getDetails();
```

## Pillars of Object-oriented Programming

There are four main pillars of Object-oriented programming, they are:

- Abstraction
- Polymorphism
- Encapsulation
- Inheritance

### Abstraction

Think of your mobile device or your computer as an object, your mobile device or computer has a complex circuit board inside of it and buttons or touch screens on the outside that you interact with (interface). as a computer user, you don't need to know the working principles behind its operation to use it for your purpose or use case. all the complexities of the circuit board are hidden from you. This is what is referred to as abstraction. displaying only essential information and hiding the details.

We can do the same thing for our object in a computer program by hiding some properties and methods from outside usage and exposing only the essentials.

The way to hide the details of a class is by creating private properties and methods.

#### Example: 
let's understand abstraction using an example.
 

```
function Box(length, breadth, height) {

this.length = length;

this.breadth = breadth;

this.height = height;

this.defaultPosition = { x: 0, y: 0};

this.computeOptimumPosition = function() {

console.log('compute the best positon');

} this.draw = function() {

this.computeOptimumPosition();

console.log('draw');

}

} const box1 = new Box(55, 22, 35);

console.log(box1.defaultPosition)

box1.computeOptimumPosition()
```
let's say for example we don't want consumers of this object to have access to `computeOptimumPosition()` function and the `defaultPosition` property, we can do that by abstracting it way (that is by declaring them as private properties so that consumers of the class can't have direct access to it). the process of making these properties private is known as **abstraction**.

#### Example:
 let's make these properties private

the way to make` computeOptimumPosition() `function and the `defaultPosition` variable private is by declaring them as local variables inside of the constructor function making them go out of scope outside of the function. with this technique, we can hide certain members of the class from the outside.

```
function Box(length, breadth, height) {

this.length = length;

this.breadth = breadth;

this.height = height;

let defaultPosition = { x: 0, y: 0};

let computeOptimumPosition = function() {

console.log('compute the best positon');

} this.draw = function() {

// ensure you remove this keyword here too

computeOptimumPosition();

console.log('draw');

}

} const box1 = new Box(55, 22, 35);

console.log(box1.defaultPosition) // trying this out will result in an error

box1.computeOptimumPosition() // trying to do this will result in an error

```

so by removing the` this` keyword and declaring them as local variables using the `let` the keyword, we've been able to make them private.

#### 
Benefits of abstractions

**Simpler Interface:** simple interface by exposing only the essentials

**helps to reduce the impact of change:** that is changing a private property or method won't have any external effect.

### Encapsulation

Encapsulation is the wrapping up/binding of data and function into a single unit called a class. encapsulation helps keep an object's internal state (member variables or data) private so that it can only be accessed by the object's methods (member functions), and not from other objects. These functions (member methods) facilitate object-to-object communication within your program.

### Inheritance

Inheritance is a way of reducing redundant code and ensuring reusability within your program. It is a phenomenon in which some properties and methods of an Object are being used by another Object. In other object-oriented programming languages, classes inherit from other classes, but in JavaScript, it is quite different (Objects inherit from other Objects ( certain features; properties and methods of one object can be reused by other Objects).

**Example:** let's understand inheritance with an example


```
// Inheritance example -- the function of the constructor method is to initialize the member variables of the class (name and gender)

class Person {

constructor(name, gender) {

this.name = name;

this.gender = gender;

// method to return the string

toString() {

return `Name of Person: ${this.name} and he is a ${this.gender}`

}

}

class Student extends Person {

constructor(name,gender, id) {

// super keyword for calling the above class constructor

super(name,gender);

this.id = id;

}

toString() {

return ${super.toString()}, Student Gender: ${this.gender}, Student Id: ${this.id}; }

}

let student1 = new Student('James', 'Male', 552);

console.log(student1.toString());
```
In the above example, we define a `Person` Object with properties; name, gender and method `toString()` and then we inherit the `Person` Object in the `Student` Object and use all the properties and methods of the` Person` Object as well as define certain properties and methods for the` Student` Object.

### Polymorphism

Polymorphism is one of the core concepts of object-oriented programming languages. The Word Poly means many and morph means forms. so polymorphism means many forms. in object-oriented programming, it means various objects can share the same method, but also can override shared methods with a more specific implementation. using a real-life example, a Man can be a Student, a Doctor, etc. So a Man can perform different operations at the same time. Polymorphism can be achieved by method overriding and method** overloading**.

overloading means the same function with different signatures (parameters and return values are referred to as signatures of a function).

In the above code example, The `Person` and `Student` objects both have the same method (i.e `toString()`), this is called Method Overriding. Method Overriding allows a method in a child class to have the same name** (polymorphism) **and method signature as that of a parent class.

## Summary

This article has described the basic features of object-oriented programming using JavaScript. In the next article, we'll look at the features JavaScript provides to support object-oriented programming.