Hi, my name is Abida an experienced website designer. I am learning advanced Object Oriented JavaScript concepts and Angular from ADMEC Multimedia Institute because these are the points where I lack most and so I decided to share what I learnt here from Ravi Sir. Hope you guys will be able to clear some doubts from my tiny efforts.
Actually Object Oriented JavaScript (OOJS) is the most popular term among JavaScript developers whether they are new or experienced. OOJS is quite fascinating term for every one so it is necessary to reveal some secrets of it in easy and practical way so that you can clear your all the doubts quickly related to that.
Object in JavaScript
- The basis of object oriented programmings are the “objects” that your code works with (hence the name for this programming style).
- Each object can have properties and methods.
- The properties basically hold values associated with the object while the methods provide the definitions of how the object can be acted on which can include changing the values of the properties
- Properties are variables created inside an object and methods are functions created inside an object.
Benefits of Object Oriented Coding
- Abstraction an encapsulation. What this means is that once we have created an object we can interface with that object entirely using its public methods and properties without any regard for how the object does what it does.
- Using object oriented coding makes your code more modular and less likely that different sections of code will clash with one another.
- Object oriented programming allows you to build on what you already have defined when creating new objects that have a hierarchical relationship to one another.
- You can add new properties and methods to existing objects at any time and they will be instantly available both to that object and to all objects that have been derived from that object.
Ways to Create an Object
There are two ways to create a JavaScript object. They are:
- Constructor functions – Preferred when multiple instances are required.
function NewObject(){ //code here }
How to use – You need to instantiate (create a new instance of) the object first; you do this by typing:
var myNewObject = new myObject();
myNewObject.functionName();
Example:
function Supermarket(){ this.fruits = "Apples"; this.price = "Rs60"; this.sell = function(){ alert(this.fruits+" are sold at "+this.price+" per Kg"); } } var instance1 = new Supermarket(); instance1.sell();
- Literal notation – Preferred for singleton objects.
var NewObject = { //code here }
How to use – You simply use it by referencing its variable name, so wherever it is required you call it by typing:
ObjectName.functionName();
Example:
var Supermarket = { fruits : "Apples", price : "Rs60", sell : function(){ alert(this.fruits+" are sold at "+this.price+" per Kg"); } } Supermarket.sell();
Passing arguments to constructor functions
We can pass arguments as well in the following manner:
function Supermarket(location){ this.loc = location; this.fruits = "Apples"; this.price = "Rs60"; this.sell = function(owner){ alert(this.fruits+" are sold at "+this.price+" per Kg at "+ this.loc+" owned by "+ owner); } } var instance1 = new Supermarket('Delhi'); instance1.sell('Mr ABC');
Features of OOJS
Inheritance
Inheritance uses prototype property to inherit the methods and props of parent class.
childClass.protoype = new parentClass();
Prototype
The JavaScript prototype property allows you to add new attributes to an existing prototype.
Example:
//Inheritance function parentClass(){ this.name="John"; this.parentMethod1 = function(){ return("this is a method of parent class"); } } function childClass(){ this.surname = "Doe"; this.childMethod1 = function(){ return("this is a method of child class"); } } childClass.prototype = new parentClass(); //Make the child class inherit the characteristics of parent class var createInstance = new childClass(); //create new instance of child class alert(createInstance.parentMethod1()); //Access the method of the parent class using the child class instance.Result: this is a method of parent class childClass.prototype.nationality = “English”; // Add property to an existing object using prototype. alert(createInstance.nationality); // Result: English
Encapsulation
Data hiding is the ability of objects to shield variables from external access. It is a useful consequence of the encapsulation principle. Access to other variables can be allowed but with tight control on how it is done. Methods can also be completely hidden from external use.
Abstraction
Abstraction is the ability to define an object that can represent abstract entities which can work, change state and communicate with other entities. I have given an example of abstraction at the end of this text.
Polymorphism
Polymorphism is another primary concept of Object Oriented JavaScript which doesn’t need more attention as it is managed automatically here. Let me explain it, suppose you have two objects one is parent and other one is child of it. If both objects have some properties or methods in common then child object overrides the parent’s attributes completely automatically. You don’t need to use any keywords like Java and C++.
Example:
function Obj1(){ this.name = 'admec multimedia institute'; this.url = 'https://www.admecindia.co.in' } function Obj2(){ this.url = 'http://www.web-development-institute.com' } //inheritance Obj2.prototype = new Obj1(); var myObj2 = new Obj2(); console.log(myObj2.url); // http://www.web-development-institute.com console.log(myObj2.name); // admec multimedia institute
Conclusion: You can see that we are getting the child object url value not the parent object. So it is how overriding works in Object Oriented JavaScript.
Composition
Composition occurs when you use an object by instantiating directly inside one object. Because you can not expect multiple inheritance in JavaScript so composition is the best way to use multiple objects’ attributes.
Example:
function Obj1(){ this.name = 'admec multimedia institute'; this.url = 'https://www.admecindia.co.in' } function Obj2(){ //composition of an object var myObj1 = new Obj1(); this.detail = myObj1.url + “ is the url of “ +myObj1.name; } var myObj2 = new Obj2(); console.log(myObj2.detail); // https://www.admecindia.co.in is the url of admec multimedia institute
Conclusion: In composition objects share their values but not as in inheritance. In inheritance objects are in a relation of child and parents while in composition there is no such relation between them.
Note: JavaScript is a single inheritance language while multiple objects can be composed easily.
Closure
What is a Closure?
There are two types of scopes in Javascript
- global Scope
- local scope
Variables can be accessed inside of a function only if it is defined globally.
Example:
var a = 5 function f() { alert(a) }
A closure is a function that has an,environment of its own. Closures can also be defined as function which has an inner function. The inner function access the variables define outside of the inner function but within the outer function.
Why is a Closure needed?
In languages that don’t support objects directly, we can have nested functions.
The outer function acts like class, the inner functions acts like methods. Local variables to the outer function acts like fields, they are accessible only to the inner functions.
In subsequent calls to inner functions, we want to maintain the state of the local-to-outer-function variables, this is where closures are needed.
All that we have to do is pass reference to any inner function via output of the outer function, to code outside the outer function, so that the variables of outer function accessed by inner function are preserved even after the outer function exits.
Example-1
function Person(){ //Outer Function var name = 'ABC'; this.getName = function(){ //inner function alert( name); // variable name is defined in outer function }; } var instance = new Person(); instance.getName(); //Result: ABC
Example-2
var counter = (function (){ var count = 0; return function (){ count++; paraId.innerHTML = count; } })(); btn.onclick = counter; //Result: count increases by 1 every time the button is clicked
Immediately-invoked function expression – IIFE
IIFE is a JavaScript design pattern which produces a lexical scope using JavaScript’s function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function. This pattern has been referred to as a self-executing anonymous function.
Lexical scoping: Variables declared outside of a function are global variables and are visible everywhere in a JavaScript program. Variables declared inside a function have function scope and are visible only to code that appears inside that function.
Example:
var counter = (function (){ var count = 0; return function (){ count++; paraId.innerHTML = count; } })(); // Added to auto execute the outer function which reads the value of variable count as 0 and returns the inner function every time the button is clicked. btn.onclick = counter; //Result = On every click, the count increases by 1. Another way of invoking IIFY is as follows- var list = document.getElementById("list"); for (var i = 1; i <= 5; i++) { var item = document.createElement("li"); item.appendChild(document.createTextNode("Item " + i)); item.onclick = (function (i) { return function(){ alert("Item " + i + " is clicked."); } })(i); list.appendChild(item); } //Result = Clicking on the item, gives the item number.
The variable which has to have a separate scope for each loop is passed as a parameter. This makes the value of i unique for every for loop.
Abstraction
If a class disallows calling code from accessing internal object data and forces access through methods only, this is a strong form of abstraction or information hiding known as encapsulation.
Example:
(function (){ var createWorker = function (){ var workCount = 0; var task1 = function (){ workCount++; console.log("task1 "+workCount); } var task2 = function (){ workCount++; console.log("task2 "+workCount); } return { job1:task1, job2:task2 } } var worker = createWorker(); worker.job1(); worker.job2(); })(); // Result = task11 and task22
In this example, the functions “task1” and “task2” are passes to another object instead of accessing it directly and that object is called through an instance of it. In this manner, we are encapsulating the information of the function from being altered from any public user. Only the function definition can be called from the reference of it. This is called Abstraction.
apply()
Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.
Syntax: apply([thisObj[,argArray]])
Parameters:
thisObj
Optional. The object to be used as the this object.
argArray
Optional. A set of arguments to be passed to the function.
Example:
function myFunction(a, b, c) { return a * b * c; } var myArray = [10, 2, 6]; var myObject2 = myFunction.apply(myObject2, myArray); alert(myObject2); // Will also return 20
call()
Calls a method of an object, substituting another object for the current object. The call method is used to call a method on behalf of another object. It allows you to change the thiobject of a function from the original context to the new object specified by thisObj.
If thisObj is not supplied, the globa lobject is used as thisObj.
Syntax:- call( [thisObj[, arg1[, arg2[, [, argN]]]]])
Parameters:
thisObj
Optional. The object to be used as the current object.
arg1, arg2, , argN
Optional. A list of arguments to be passed to the method.
Example:
function Product(name, price) { this.name = name; this.price = price; if (price < 0) { throw RangeError('Cannot create product ' + this.name + ' with a negative price'); } } function Food(name, price) { //composition /*var myProd = new Product( name, price); this.price = myProd.price; this.name = myProd.name;*/ this.category = 'food'; } function Toy(name, price) { //inheritance Product.call(this, name, price); this.category = 'toy'; } var cheese = new Food('feta', 5); var fun = new Toy('robot', 40); alert(cheese.name); //undefined alert(cheese.price); //undefined alert(fun.name); //robot var myProd = new Product('Pizza', 110); alert(myProd.name); //pizza
bind()
We use the Bind() method primarily to call a function with the this value set explicitly. In other words, bind () allows us to easily set which specific object will be bound to this when a function or method is invoked.
Below is an example which states the usage of apply, call and bind.
var obj = { num:2 } var addTo = function( a, b, c ){ return this.num + a + b + c; } var arr = [ 2, 1, 4 ]; alert(addTo.call( obj, 2, 3, 4)); alert(addTo.apply( obj, arr)); var bindFunc = addTo.bind( obj ); alert(bindFunc( 2, 4, 6 ));
Summary
Object Oriented JavaScript (OOJS) is really a fantastic topic to discuss. I have added some practical examples too for the better understanding. When you have a moderate size application then OOJS is a boon for providing the code architecture with great simplicity and modularity.
OOJS enables scalability and maintainability by reducing the repeating of the code.
View Full Presentation on slideshare:
Loops in JavaScript
Loops in java script from ADMEC Multimedia Institute