Handling OOPS with Javascript with examples

Today we are going to learn about OOPs (Object Oriented Programming). But before going forward in advance concept of javascript, Lets understand why javascript is getting popular day by day. Below are some of the facts about javascript that makes it very popular:

  • Its lightweight. Since its available at client side so its doesn’t go to server for further loading of apps.
  • With the emerge of mobile technology, HTML5 or similar tech are most in demand . These new technologies are embeded with JS only like HTML5 means HTML +JS .
  • With javascript based REST implementation now objects are able to traverse from client to server.
  • In todays area javascript is being used at client side as well as server side.
  • In the upcoming days everything would be UI.
  • In earlier days Javascript was only for validation but todays it can utilize the feature of oops.
  • Json (Javascript based object notation) has given an option of object mapping and seamless object traverse from client to server.

The above facts are sufficient to give us courage to learn about OOPs implementation with Javascript. So todays article we will learn about below :

  1. How to create Class and Object with Javascript.
  2. How to use inheritance with Javascript
  3. How to use Polymorphism with Javascript
  4. How to use Encapsulation with Javascript
  5. How to use Overloading with Javascript
  6. How to use Overriding with Javascript
  7. What is closure in Javascript and what is the advantage of closure.

Note: By default Javascript is not in built with OOPs concept but we have achieved it through certain techniques . That we will see below.

How to create Object with Javascript:

We can create object with Javascript by 2 ways.

  1. Object Creation Using Constructor function
  2. By using prototyping model
    • Example of Object Creation using Constructor Notification

Try demo here (Create Object)


var Employee = function(firstName,lastName,age,eyeColor)

{

               this.firstName = firstName;

               this.lastName = lastName;

               this.age = age;

               this.eyeColor = eyeColor;

}

var Emp = new Employee("John","Doe",50,"blue");

Explanation: This is just like a simple function. Just the only difference with simple function is that you are returning an anonymous function to a variable . This variable will be treated like a class. In the next line

var Emp = new Employee(“John”,”Doe”,50,”blue”);

You can see we are creating an object of this class (that is an anonymous function)

  • Example of Object Creation using Prototyping model

1.2.1: Using null prototype model


var Emp = Object.create(null); //Prototype

Emp.firstName= "John";

Emp.lastName= "Doe";

Emp.age= 50;

Emp.eyeColor= "blue";

1.2.2 : Using Prototyp model anonymous function


var Employee = {

   eyeColor : "Blue",

   setEmployeeDetails : function(firstName,lastName,age) {

        this.firstName = firstName;

        this.lastName = lastName;

        this.age = age;

        }

};

var Emp = Object.create(Employee); //Protype

Emp.setEmployeeDetails("John","Doe",50);

1.2.3: Create a null object and then assign values into it


var Emp = new Object();//Objectob

Emp.firstName= "John";

Emp.lastName= "Doe";

Emp.age= 50;

Emp.eyeColor= "blue";

alert("FirstName="+Emp.firstName+" Lastname="+Emp.lastName+" age ="+Emp.age+" Eyecolor="+Emp.eyeColor);

  1. Object literal Notification

Explanation:

Here we are utilizing prototyping model of the javascript that gives us the facility to create null object at any time and we can expand it anywhere based on our requirement.

  1. Example of Inheritance implementation using javascript

Try demo here (Inheritance)


var Employee = {

   eyeColor : "Blue",

   setEmployeeDetails : function(ObjEngineer) {

               this.firstName = ObjEngineer.firstName;

               this.lastName = ObjEngineer.lastName;

               this.age = ObjEngineer.age;

               this.tech = ObjEngineer.technology;

               }

};

//Add new method to existing class

Employee.display = function ()

{

alert("firstName="+this.firstName+"lastName"+this.lastName+"age="+this.age+"technology"+this.tech);

}

var Engineer = function(tech,firstName,lastName,age){

               this.technology = tech;

               this.firstName = firstName;

               this.lastName = lastName;

               this.age = age;

   Employee.setEmployeeDetails(this);//Inherited function

   Employee.display();//Inherited function

}

var ObjEngineer = new Engineer("PHP","CS","Pandey",30);

           

Explanation:

Inheritance means you can use parent class function under child class. Here in the above example you can see you are achieving same thing at your child class Employee See. Employee.setEmployeeDetails

Multiple inheritance is not possible in javascript. Because it creates unnecessary ambiguity.

  1. Example of how to achieve polymorphism using Javascript

Try demo here (Polymorphism)


function Person(age, weight) {

this.age=age;

this.weight=weight;

this.getInfo=function() {

return "I am " + this.age + " years old " +

               "and weighs " + this.weight +" kilo.";

}

}

function Employee(age, weight, salary){

this.salary=salary;

this.age=age;

this.weight=weight;

this.getInfo=function() {

return "I am " + this.age + " years old " +

               "and weighs " + this.weight +" kilo " +

               "and earns " + this.salary + " dollar.";

}

}

Employee.prototype= new Person();

Employee.prototype.constructor=Employee;

// The argument, 'obj', can be of any kind

// which method, getInfo(), to be executed depend on the object

// that 'obj' refer to.

function showInfo(obj) {

document.write(obj.getInfo()+"<br>");

}

var person = new Person(50,90);

var employee = new Employee(43,80,50000);

showInfo(person);

showInfo(employee);

Explanation:

Polymorphism means using more than one function with different parameter and function will behave separately based on number of arguments. In the above demo we are using same name function in parent and child class. Here the important point is that in javascript we can use the function within that function scope only. Unlike C,C++ or Java child class doesn’t contain reference of parent class. That’s why its known as psudo implementation.

We can have only dynamic polymorphism . We can’t implement static polymorphism because javascript is not a compiled language. It works on run time only.

  1. Example of Encapsulation using Javascript

Try demo here (Encapsulation)


/*Here Engineer doesn't kow that its being called from Employee class. JS only have dynamic polymorphism*/

var Employee = {

   eyeColor : "Blue",

   setEmployeeDetails : function(ObjEngineer) {

               this.firstName = ObjEngineer.firstName;

               this.lastName = ObjEngineer.lastName;

               this.age = ObjEngineer.age;

               this.tech = ObjEngineer.technology;

               }

};

//Add new method to existing class

Employee.display = function ()

{

alert("firstName="+this.firstName+"lastName"+this.lastName+"age="+this.age+"technology"+this.tech);

}

var Engineer = function(tech,firstName,lastName,age){

               this.technology = tech;

               this.firstName = firstName;

               this.lastName = lastName;

               this.age = age;

   Employee.setEmployeeDetails(this);//Inherited function

   Employee.display();//Inherited function

}

var ObjEngineer = new Engineer("PHP","CS","Pandey",30);

Explanation:

Encapsulation means hiding unnecessary details from object. Only the user should be aware about his/here functionality he is not bothered about their internal implementation. Here Engineer doesn’t know that its being called from Employee class. JS only have dynamic polymorphism

  1. How to achieve overloading through Javascript

Since Overloading is a part of static polymorphism, So it can’t be done using javascript. Only overriding is possible

  1. How to achieve overriding using javascript
  2. What is Closure

Before understanding closure we need to understand that javascript has two types of scope

  1. i) Local : This type of variables can’t be accessed outside of function.
  2. ii) Global: This kind of variable would be applicable throughout the application.

 

But if we are going to create a robust architecture then we should have a strong and restricted use of variables . It means if we want variable of a function should be used by more than one function then we can use becuase allowing them as global is not safe for the application life cycle.

 

To understand the concepts lets understand the concept of lexical scoping

Try demo here (Lexical Scoping)


/*Dispaly will have name if its under init. If it goes outside that init function you can't get it. For this reason you need the concept of colsure*/

function init()

{

               var name="Mozilla"; // Local variable

               function displayName()

               {

                              alert(name);

               }

               displayName();

}

init();

Explanation:

Here variable ‘name’ would be only available under function init as well as under DisplayName. We can’t utilize it outside until we declare it global. But declaring it global is not safe. So here is the concept of closure comes.

  1. Example of Closure Implementation

Try demo here (Closure)


/*You can use every part of a function even outside of a function*/

function init()

{

               var name="Mozilla";

               function displayName()

               {

                              alert(name);

               }

               return displayName;

}

var custominit = init();

custominit();

Explanation: Here you can use every part of a function even outside of a function without declaring it as global. So the concept of closure is a closure can riturn all the member variable as well as member function of an object for further use without declaring it as global.

 

  1. http://jsfiddle.net/cshekhar/ebx4kbf7/ – Create Object
  2. http://jsfiddle.net/cshekhar/L6mgLzc3/ -Inheritance
  3. http://jsfiddle.net/cshekhar/r5pdnyun/ – Polymorphism
  4. http://jsfiddle.net/cshekhar/qb6yb7sf/ – Encapsulation
  5. http://jsfiddle.net/cshekhar/qv5s62ze/1/ – Lexical Scoping
  6. http://jsfiddle.net/cshekhar/6n5d8z0c/ -Closure
The following two tabs change content below.

Chandra Shekhar

GCP Architect
Chandra Shekhar Pandey is Google certified Cloud engineer, I am Magento2 Trained developer. Having huge experience in designing cloud solution. I have around 12 years of experience with world enterprise IT companies and fortune 500 clients. During my architecture design I am always caring about high availability, fast performance and resilient system. From the programmer background I have huge experience in LAMP stack as well. Throughout my carrier I have worked on Retail, E-Learning, Video Conferencing and social media domain. The motive of creating cutehits was just to share the knowledge/solutions I get to know during my day to day life so that if possible I can help someone for same problems/solutions. CuteHits.com is a really a very effort for sharing knowledge to rest of the world. For any query/suggestion about same you can contact me on below details:- Email: shekharmca2005 at gmail.com Phone: +91-9560201363

Latest posts by Chandra Shekhar (see all)

You may also like...