A Beginner to Object Oriented Programming in JavaScript

A Beginner to Object Oriented Programming in JavaScript

For the Purpose of this article, OOP means Object Oriented Programming

I came from a C# background as developer, however jumping into JavaScript I did not really get OOP concepts as it seemed different from the regular scary class accessifiers in c-sharp and "this" keyword. It was all a different ball game (maybe because of I did not understand OOP as i taught i did)

I am writing this article on OOP hoping that anyone transiting from any Language to JS or a total beginner to programming will understand the concept of OOP and also apply it to Javascript.

java-oops.png

What exactly is OOP:

Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.

OOP focuses on the objects that developers want to manipulate rather than the logic required to manipulate them.

So let's dive into the code:

1. Objects: In JavaScript, an object is a standalone entity, with properties and type. Compare it with a dog, for example. A dog is an object, with properties. A dog has a color, a hair, weight, a name etc. The same way, JavaScript objects can have properties, which define their characteristics.

So we can write

var dogName="marshall";
var dogColor="yellow"
var dogHeight=67

The block above contains different pieces of information for one Dog, it could be otherwise written with the help of objects as:


var dog = {
name : "Marshall",
color : "yellow",
height : 67
}

name, color, height are object properties/key pairs. The dog is an object that describes the properties of dogs.

We can now access the dog properties using

console.log(dog.name) //Marshall
console.log(dog.color) //yellow
console.logg(dog.height) //67

So we did a basic review of Objects so we can properly understand "this" keyword as it regards OOP.

Note: The characteristics of an Object are called as Property, in Object Oriented Programming and the actions are called methods. An Object is an instance of a class. Objects are everywhere in JavaScript almost every element is an Object whether it is a function, arrays and string.

Functions in Objects: Properties could also contain functions, which we then call methods.

//Defining object
let person = {
    first_name:'Mukul',
    last_name: 'Latiyan',

    //method
    getFunction : function(){
        return (`The name of the person is
        ${person.first_name} ${person.last_name}`)
    },
    //object within object
    phone_number : {
        mobile:'12345',
        landline:'6789'
    }
}
console.log(person.getFunction()); //The name of the person is Makul Latiyan
console.log(person.phone_number.landline); //6789

2. Constructors

A constructor is a function that creates an instance of a class which is typically called an “object”. In JavaScript, a constructor gets called when you declare an object using the new keyword. The purpose of a constructor is to create an object and set values if there are any object properties present.

A Method in JavaScript is a property of an object whose value is a function. Object can be created in two ways in JavaScript: i) Object literals (which we did above) ii) Object Constructor

Object Constructors are like schemas which we can use to create more objects with similar properties. So they more like templates models we use to create different objects based on our input at time of initialization.

//using a constructor
function person(first_name,last_name){
   this.first_name = first_name;
   this.last_name = last_name;
}
//creating new instances of person object
let person1 = new person('Mukul','Latiyan');
let person2 = new person('Rahul','Avasthi');

console.log(person1.first_name); //Makul
console.log(`${person2.first_name} ${person2.last_name}`);  //Rahul Avasthi

Explanation: So we basically define our template using the person function and then we initialize the person function as new person() and parse in the needed arguments which produces result as that of the template.

Ehm! I think you are a bit confused with "this" keyword and how we suddenly transited into functions as object, not too worry in this article you will get to understand better.

This Keyword: I remember when I set out to learn JS and I asked a lot of questions about "this" to some I found answers while to some i didn't get detailed explanations, however I can assume that anyone that understands "this" completely understands JS completely too.

But for the purpose of this article i will try my best to explain it properly as it relates to OOP

object-class-javascript-min.png

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
        return this.firstName + " " + this.lastName;
    }
};

In a function definition, "this" refers to the "owner" of the function. In the example above, this refers to the person object. The person object "owns" the fullName method. The 'this' keyword let’s us store unique values created for each instance of object we create from the template.

The new keyword allows us to create instances( new objects ) with the properties already stated in the constructors.

Note: the this keyword makes it possible that values passed to the constructor function can be accessed by other methods in the class.

This basically means if I have

class Vehicle {
  constructor(name, maker, engine) {
    this.name = name;
    this.maker =  maker;
    this.engine = engine;
  }
console.log(this)
}

This means I am storing the values parsed into the constructor to not just be private alone to be constructor but I am storing it an object called "this" that is internal to the class in JavaScript.

Further Explanation:

class Vehicle {
  constructor(name, maker, engine) {
    this.name = name;
    this.maker = maker;
    this.engine = engine;
  }
  getDetails() {
    console.log(this);
  }
}
// Making object with the help of the constructor
let bike1 = new Vehicle("Hayabusa", "Suzuki", "1340cc");
bike1.getDetails(); // {name: 'Hayabusa', maker: 'Suzuki', engine: '1340cc'}

In our constructor method we set all the values we are parsing into to be values of the keys of the "this" keyword. So let us simplify this further. Before all the initialization this is set to a global window object perhaps try opening your console in chrome and type console.log(this)

But when we run bike1.getDetails(); from the code below which returns console.log(this) We get an Object that looks like this

{name: 'Hayabusa', maker: 'Suzuki', engine: '1340cc'}

Which means this actually equals the above object that is why we can access the name using this.name because from our constructor we set name to be a key pair for this.

Basically this allows us access our constructor arguments/parameters by other functions that are not constructors.

3. Classes: Classes are blueprint of an Object. A class can have many Object, because class is a template while Object are instances of the class or the concrete implementation. Before we move further into implementation, we should know unlike other Object Oriented Language there is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based object oriented language, which means it doesn’t have classes rather it define behaviors using constructor function and then reuse it using the prototype.

Note: Even the classes provided by ECMA2015 are objects.

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

// Defining class using es6
class Vehicle {
constructor(name, maker, engine) {
    this.name = name;
    this.maker = maker;
    this.engine = engine;
}
getDetails(){
    return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Chibuze', 'Sam', '1340cc');
let bike2 = new Vehicle('Lizzy', 'Oluchi', '998cc');

console.log(bike1.name); // Chibueze
console.log(bike2.maker); // Oluchi
console.log(bike1.getDetails()); //The name of the bike is Chibueze

The 4 Pillars of OOP

OOP-graphic-blog-oop-concepts-in-java-what-is-object-oriented-programming.png

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

1. Encapsulation: In object-oriented computer programming languages, the notion of encapsulation (or OOP Encapsulation) refers to the bundling of data, along with the methods that operate on that data, into a single unit.

No external factor can change the internal methods or functions of the class only properties and functions defined within the class can.

Let us take a look at a practical example:

//encapsulation example
class person{
    constructor(name,id){
        this.name = name;
        this.id = id;
    }
    add_Address(add){
        this.add = add;
    }
    getDetails(){
        console.log(`Name is ${this.name},Address is: ${this.add}`);
    }
}

let person1 = new person('Mukul',21);
person1.add_Address('Delhi');
person1.getDetails();

2. Abstraction: Abstraction is the concept of object-oriented programming that "shows" only essential attributes and "hides" unnecessary information. The main purpose of abstraction is hiding the unnecessary details from the users

// Abstraction example
function person(fname,lname){
    let firstname = fname;
    let lastname = lname;

    let getDetails_noaccess = function(){
        return (`First name is: ${firstname} Last
            name is: ${lastname}`);
    }

    this.getDetails_access = function(){
        return (`First name is: ${firstname}, Last
            name is: ${lastname}`);
    }
}
let person1 = new person('Samuel','Chibueze');
console.log(person1.firstname); //undefined
console.log(person1.getDetails_noaccess); //undefined
console.log(person1.getDetails_access());  // First name is: Samuel, Last
            name is: Chibueze

Explanantions: console.log(person1.getDetails_noaccess); returns undefined because it is not a object value of the person function, same with console.log(person1.firstname) . But like i explained earlier the this keyword does the magic, here by making getDetails_access an internal accessible property of the person function.

Abstractions aims at us showing only essential attributes and "hides" unnecessary information

3. Inheritance:

inheritance.png

As the name implies, inheritance is simply inheriting attributes and methods from one class to another class, so an animal has certain properties like they can walk, eat, sleep etc. Instead of writing a function each for each animal we can do define an animal class and define the generic properties of an animal inherit the generic properties like walk, eat, sleep then access the for animals like sharks and dogs since they have different methods of reproduction we can write functions for them like a reproduction function which may be different for each class.

We define the person class

//Inhertiance example
// A persons class
class person{
    constructor(name){
        this.name = name;
    }
    //method to return the string
    toString(){
        return (`Name of person: ${this.name}`);
    }
console.log(this.toString())
}

We inherit the properties of the person class to form the student class since student has characteristics of a person

class student extends person{
    constructor(name,id){
        //super keyword to for calling above class constructor
        super(name);
        this.id = id;
    }
    toString(){
        return (`${super.toString()},Student ID: ${this.id}`);
    }
}
let student1 = new student('Mukul',22);
console.log(student1.toString());

So we encountered something new here Super! It personally took me time to understand perhaps just because of i taught it was difficult.

WRh0J.jpg

Super basically let's us access constructor values of the parent class by basically calling the function with the argument parsed in into the parent constructor so it can be accessed by the child class.

4. Polymorphism:

Note: The Person and Student object both have same method i.e toString(), this is called as Method Overriding. Method Overriding allows method in a child class to have the same name and method signature as that of a parent class. In the above code, super keyword is used to refer immediate parent class instance variable.

Polymorphism is nothing but one type but many forms. One type of object can behave differently depending upon the runtime scenario. Polymorphism uses the concept of Inheritance to achieve this. In polymorphism, multiple objects will have the same method but different implementation and depending upon the user preference the corresponding object will be selected and the method corresponding to that object will be executed. This is also known as method overriding.

Refereneces and Further Reading.

geeksforgeeks.org

amara.hashnode.dev

Thank you for reading this article.

KwftHd6Bl.png