Introduction to Object Oriented Programming in JavaScript

·

13 min read

Object Oriented Programming is a model in computer programming that actually works with data and objects rather than the logic required to manipulate them.

Object Oriented programming is useful in handling large, complex and actively updated programs, like programs for manufacturing and design and programs for mobile or web applications.

JavaScript is a prototype-based language, but regardless of this fact it is also implements the Object-Oriented Programming model. In this article I am going to explain how JavaScript implements OOP using some basic concepts of OOP.

In this article you are expected to see the following:

Outline

i) Definition and basic concepts of OOP

ii) Objects in JavaScript

iii) Classes in JavaScript

iv) Encapsulation in JavaScript

v) Inheritance in JavaScript

vi) Conclusion

Definition and Basic Concept of OOP

By definition Object Oriented Programming also known as OOP for short is a model in computer programming that organizes software design in terms of data and object. OOP model is more interested in Objects rather than the logic behind manipulating these Objects.

OOP makes collaborative development efficient, because projects are divided into groups and it also adds to code readability, scalability and efficiency.

We have other types of programming methods, like the functional programming that is based on dividing programs into subprograms called functions and logical programming which is based on logic and flow control. But these methods are outside the scope of this article, what we are focusing on is Object Oriented Programming.

There are important concepts in Object Oriented Programming model that you have to be familiar with in order to implement this model in JavaScript properly, they include:

i) Objects

ii) Classes

iii) Encapsulation

iv) Inheritance

These concepts are the major key concepts that classify a language as OOP. I am going to explain these concepts using JavaScript.

So, let’s get started.

Objects in JavaScript

Objects are special kinds of entities that possess some kind of properties and have methods that can be applied to them. Objects in programming can also be compared with real life entities. Like a person for instance, a person can have certain characteristics like eye-color, complexion, height etc. and also a person can perform certain actions such as running, Jumping, walking, talking etc. The same thing applies to programming objects. In programming, these characteristics are called properties of the object and the actions are called methods. In JavaScript almost every element is an object. Ranging from arrays, strings and even functions. No matter the data type they all have properties and methods that can be applied to them.

To create an object instance in JavaScript you can apply any of these two formats:

i) Object Literal

let person ={

    firstname:'Mikel',

    lastname:'Johnson',
}

An Object in JavaScript accepts properties in a key-value pair format. So, if you check the person Object on the console by saying console.log like this:

let person ={

    firstname: 'Mikel',

    lastname: 'Johnson',
}
console.log(person)

You will see everything we have inside the person object on the console.

So, from our example, the person Object have two properties (the firstname and lastname).

You can access a specific property inside the person object. For example, let’s say you want to access the firstname property you can simply do the following:

let person ={

    firstname:'Mikel',

    lastname:'Johnson',

}

console.log(person.firstname)

This will give an output of the value associated with the firstname property, which is ‘Mikel’. There are other methods of accessing the properties of an object. You can also do this:

let person ={

    firstname:'Mikel',

    lastname:'Johnson',

}

console.log(person[‘firstname’])

this will also give ‘Mikel’ on the console.

You can also delete properties from the object using the delete keyword like this:

let person ={

   firstname: 'Mikel',

    lastname:'Johnson',
}

delete person.firstname

Now, the firstname property is no longer inside the person object, you can check it out on the console by applying the console.log.

Another method you can use in defining an object is

ii) Object constructor

So, from the previous examples you saw how to define objects for single entities, that is to say we only created a one-person object, that has a firstname and secondname property. So, what if you want to add a second person object with the same type, that is we want to add a second object that has a firstname and a secondname, well from the previous example this won’t be readily possible, we do not have a blueprint that can allow us to create multiple object of the same type.

This is where the Object constructor comes in. An Object constructor is used for creating something like a blueprint for an object type, so whenever you create a new object instance using the Object constructor name, that object instance will contain the same properties in the blue print.

So, to create an object type using the Object constructor you need to follow this syntax:

function Person(firstname, lastname, age){

    this.firstname = firstname;

    this.lastname = lastname;

    this.age = age

}

In order to create the blueprint you need to make use a function, so you will first of all declare a function with the name of the object you intend to create a blueprint for, in our case we want to create a blueprint for the person object, that explains why we have the name of our function as “Person”. Also note that it is a good practice to always have the name of the object function name start with an uppercase letter, which is why we have ours starting with an uppercase “P”.

After declaring the object constructor function. You have to pass some properties that you want the object to have, like the firstname, secondname and age in our case, You, can achieve this by using the “this” keyword.

So now we have a blueprint of what we want our object to look like, it is time to create the actual object. To create an Object instance, you make use of the new keyword followed by the name of the function name, so in our case we have something like this:

function Person(firstname, lastname, age){
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age
}
const maleFriend = new Person("John", "Daniel", 21)
console.log(maleFriend)

So, if you check the console, you will see all the properties we listed in the blueprint (ie “firstname”, “lastname” and “age”) and their respective values in the Person object we just created assigned to them. Something like this:

  1. age: 21
  2. firstname: "John"
  3. lastname: "Daniel

Now with this I can go ahead and create another Person instance, let’s say you have a female also you can simply go below your maleFriend and add an object instance for your female friend like this:

function Person(firstname, lastname, age){
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age
}
const maleFriend = new Person("John", "Daniel", 21)
const femaleFriend = new Person("Jessica", "Albert", 18)
console.log(femaleFriend)
console.log(maleFriend)

Now if you should check this on the console, you will find out that you now have two instances of the Person object, one for femaleFriend and the other for maleFriend, and they all have the same blueprint (the Person object). This is how you create many instances of objects of the same type.

Classes in JavaScript

In Object Oriented Programming classes are blueprints for actual objects, so you can actually say that what we did in the previous example of creating an object, was creating a class first before creating real object instances.

So, because classes are blueprints, they can contain large amounts of objects.

JavaScript have no classes unlike in other programming languages like Java where you can find classes, well the reason for is the fact that JavaScript is a prototype-based Object-Oriented Programming language. What happens in JavaScript is that, it defines certain class behaviors using constructor functions, and then reuse it using the prototype.

So, to define a class in JavaScript, you can use the class keyword, that was introduced in ES6 or you can apply the traditional method that I showed you earlier.

Example:

i) Class keyword:

I am going to use a different example, just so you won’t get confused. Let’s say you want to create objects instances for three kinds of cars (phantom, range-rover, Ferrari), you can use the class keyword to create a blueprint (class) for them and then create the object instances.

Example:

class Car{
    constructor (name, manufacturer) {
        this.name = name;
        this.manufacturer = manufacturer;
    }
}

From the above example you will notice the use of the “this” keyword, which we used in the last example.

The “this” keyword in JavaScript refers to the object that owns the code, so whenever we create an object instance, the “this” keyword refers to that object instance. Note that the “this” keyword serves as a substitute for new object instances, when it is used inside a constructor function.

So, it is used for constructing the Object blueprint. We have just successfully created a class, now you can go ahead and create the actual object using the class name alongside the “new” keyword and everything will work out perfectly well.

Example:

class Car{
    constructor (name, manufacturer) {
        this.name = name;
        this.manufacturer = manufacturer;
    }
}
let firstCar = new Car ("Range Rover sport", "Range-rover");
let nextCar = new Car("Ferrari spider", "Ferrari");
let lastCar = new Car("Phantom", "Rolls Royce");
console.log(firstCar)
console.log(nextCar)
console.log(lastCar)

So, if you should check this on the console, you should see the properties of each object instance printed out in the console and notice how they have “name” and “manufacturer” key associated to each property inside the different object instances, this happens because we have already define a blue print using the constructor function.

ii) Traditional method

Note that prior to ES6 there was nothing like the class keyword, so defining a class was pretty much not like this. Things were done the traditional way.

In the traditional way of creating classes in JavaScript we make use of the function, like we did in creating object using object constructor.

Example:

function Car(name, manufacturer){

    this.name = name;

    this.manufacturer = manufacturer;

}

This looks like the object constructor method of defining object, well, it is but this time we are defining a class. So, now you can start creating instances of object, by using the “new” keyword alongside the name of the function.

So, this was the only way available for defining classes prior to ES6 when there was nothing like the class keyword.

iii) Encapsulation in JavaScript:

Encapsulation as a concept in OOP is a mechanism of wrapping up property and function together in one unit.

Example:

From the previous example of our Car class we can actually declare variables inside the class without assigning values to them. Like this:

class Car{
    constructor (){
        let carName;
        let manufacturer;
    }
}

So, now we have a Car class with the carName, and manufacturer variables in it. So, if we want the variables to have values, which of course we do, we will need to make use of the getters and setters methods.

The getters and setters methods are methods that acts like actual properties of a class, and they are helpful in setting and getting a specified property from a class.

So, right inside the class, you can create these methods by using the getters and setters methods like this:

class Car{
    constructor (){
        let carName;
        let manufacturer;
    }
    getCarName (){
        return this.carName;
    }
    setCarName(carName){
        this.carName = carName;
    }
    getManufacturer(){
        return this.manufacturer;
    }
    setManufacturer(manufacturer){
        this.manufacturer = manufacturer
    }
}

From the example above, we used the setCarName (setter method) function, in passing a value to the CarName variable.

So, basically what we just did was to create a blueprint for the CarName, then we will use the getCarName (getter method) function to get the name of the car, that we defined using the setCarName function, and then repeat the same thing for the manufacturer variable, using the setManufacturer and getManufacturer functions respectively.

With this we now have a complete blueprint for our car object and we can now define an actual object instance like this:

class Car{
    constructor (){
        let carName;
        let manufacturer;
    }
    getCarName (){
        return this.carName;
    }
    setCarName(carName){
        this.carName = carName;
    }
    getManufacturer(){
        return this.manufacturer;
    }
    setManufacturer(manufacturer){
        this.manufacturer = manufacturer
    }
}
let car = new Car ();
car.setCarName("Phantom");

Notice how we use the setCarName function to assign a value “Phantom” to the carName variable. If you want to check the carName variable in the console, you apply the custom “car.CarName” method that we have been using or you can apply the getCarName function like this:

class Car{
    constructor (){
        let carName;
        let manufacturer;
    }
    getCarName (){
        return this.carName;
    }
    setCarName(carName){
        this.carName = carName;
    }
    getManufacturer(){
        return this.manufacturer;
    }
    setManufacturer(manufacturer){
        this.manufacturer = manufacturer
    }
}
let car = new Car ();
car.setCarName("Phantom");
console.log(car.getCarName())

So, if you check the console. You will find “Phantom” on the console. That is the whole idea behind encapsulation. Wrapping data (in our case the variables, carName and manufacturer) and functions (in our case the setters and getters method) inside a class.

iv) Inheritance in JavaScript:

Inheritance in Object-Oriented Programming is a mechanism where a class can use certain properties or methods in another class. But in JavaScript inheritance is between objects, so unlike in other programming languages where classes inherit properties and methods from other classes, in JavaScript it is objects that inherits these properties and methods from another objects.

Let’s use a real life scenario as an example. In real life let’s say your parents included you in their will and they gave out a share of their properties to you, with this you now have full access and control over such properties, this is similar to inheritance in OOP.

In the concept of inheritance, we call the class from which these properties are inherited from a parent class, super class or base class. And the class that inherits the properties are called either a child class, sub class or a derived class. Let’s see an example.

Example:

class Car{
    constructor (name){
}
    setName(name){
        this.name = name;
    }

}

With the example above we just created a “Car” and then passed in a method (which is encapsulation by the way) that sets some kind of a name value for any object instance that would be created from this class.

In other words, if we should create an object using the methods we have been applying in previous examples, this object will contain this name property, but we are not going to do that now.

What we are going to do is to create a new class, that is going to inherit this method and also the name property from the “Car” class.

The idea behind this is you have two or three different cars, but regardless of their names they are still cars.

So, in order to inherit this property and method from the “Car” class to the new class we want to create, you will make use of the “extends” keyword like this:

class favCar extends Car{
   constructor(name){
    super(name)
    }
    speedLimit(speed){
        console.log(' The speed Limit for ' + this.name + ' is ' + speed)
}

So, we just allowed our new class to inherit properties and methods from the “Car” class using the “extends” keyword, notice how we use the “super” inside the constructor function.

Well in order to inherit a property from a super class, you have to pass in that property into the constructor function using the “super” keyword and then the name of the property as an argument, like we just did.

With this you can go ahead and create an object instance using the “favCar” class and that object will have same properties that ware provided in the “Car” class (super class).

let myCar = new favCar();

myCar.setName('Phantom');

myCar.speedLimit(200);

Adding the whole codes together, we have:

class Car{
    constructor (name){
}
    setName(name){
        this.name = name;
    }

}
class favCar extends Car{
   constructor(name){
    super(name)
    }
    speedLimit(speed){
        console.log(' The speed Limit for ' + this.name + ' is ' + speed)
    }
}
let myCar = new favCar();
myCar.setName('Phantom');
myCar.speedLimit(200);

and an output of “The speed limit for Phantom is 200”. We just successfully inherited the name property from the Car class to the favCar.

What you should always remember is that if you want to inherit a property or a method from a super class to a sub class, always use the super and extends keywords as shown.

So, with inheritance you create classes with some methods and still inherit these methods or properties to sub classes. This is very helpful, because you do not need to think of creating new methods or properties for new classes whenever you create them.

Conclusion

It was quite an eventful walk through the basic concepts of Object-Oriented Programming as it concerns JavaScript.

In this article we were able to cover key concepts such as Objects, classes, encapsulation and inheritance. You saw how you can actually pass properties and methods into a class at the same.

It was an eventful walk, and thank you so much for following up to this point and I hope this was helpful.

Please remember to share and leave your comments on the comment section down below. Corrections are accepted also. Thank you