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 :
- How to create Class and Object with Javascript.
- How to use inheritance with Javascript
- How to use Polymorphism with Javascript
- How to use Encapsulation with Javascript
- How to use Overloading with Javascript
- How to use Overriding with Javascript
- 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.
- Object Creation Using Constructor function
- By using prototyping model
- Example of Object Creation using Constructor Notification
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);
- 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.
- Example of Inheritance implementation using javascript
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.
- Example of how to achieve polymorphism using Javascript
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.
- Example of Encapsulation using Javascript
/*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
- 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
- How to achieve overriding using javascript
- What is Closure
Before understanding closure we need to understand that javascript has two types of scope
- i) Local : This type of variables can’t be accessed outside of function.
- 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.
- Example of Closure Implementation
/*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.
- http://jsfiddle.net/cshekhar/ebx4kbf7/ – Create Object
- http://jsfiddle.net/cshekhar/L6mgLzc3/ -Inheritance
- http://jsfiddle.net/cshekhar/r5pdnyun/ – Polymorphism
- http://jsfiddle.net/cshekhar/qb6yb7sf/ – Encapsulation
- http://jsfiddle.net/cshekhar/qv5s62ze/1/ – Lexical Scoping
- http://jsfiddle.net/cshekhar/6n5d8z0c/ -Closure
Related posts:
Chandra Shekhar
Latest posts by Chandra Shekhar (see all)
- Best practices for micro service design - January 23, 2022
- Spring Boot - January 23, 2022
- Java - January 23, 2022
Recent Comments