Object Oriented Programming Using JavaScript

 Look Back To The History

Late in 1990s , Brendan Eich a Netscape guy planned to put together a language that would work on browsers. LiveScript was designed as the part of this exercise. Unlike C++ and Java , this language was designed to support prototype based OOPs (The concept we are going to talk in a while).
This language was to look like Java for some reasons and hence it was named as "JavaScript".

Prototypal OOPs is conceptually different from the class based system. In OOPs we first create a class to serve as a "blue print" for the objects, then we create objects based on the blue print. This is further derived etc. Whereas the concept of Prototypal OOPs is different. We don't create class as such before hand.
Let's take a real time example:
if you were to build a chair, you would first create a blueprint on paper and then manufacture chairs based on this blueprint. The blueprint here is the class, and chairs are the objects. If you wanted to build a rocking chair, you would take the blueprint, make some modifications, and manufacture rocking chairs using the new blueprint.

Now take this example into the world of prototypes: you don’t create blueprints or classes here, you just create the object. You take some wood and hack together a chair. This chair, an actual object, can function fully as a chair and also serve as a prototype for future chairs. In the world of prototypes, you build a chair and simply create “clones” of it. If you want to build a rocking chair, all you have to do is pick a chair you’ve manufactured earlier, attach two rockers to it.

What Are We Going To Learn ?
We the going to cover the following topics :

  1. Possibility of OOPs using JavaScript
  2. JavaScript object creation and forming classes
    • Object literal
    • Function returning an object / Factory function
    • Constructor function
    • Constructor function with prototype
    • Object.Create
  3. Constructors and Object instances
  4. Class elements – fields, properties & methods
  5. Inheritance
  6. Extending JavaScript Math class
First of all we would understand the possibilities of OOPs in JavaScript. We will then try to achieve forming classes using many ways. We will talk about constructors , fields, properties, inheritance etc.


Possibilities of OOPs in JavaScript:   

              Object Oriented Programming (OOP) is meant for using self-contained pieces of code to develop applications.The self-contained code is known as Classes in most of the OOPs languages and function in JavaScript. Building applications using objects helps us adopting some important techniques i.e. Inheritance , Encapsulation etc. The two important principles with OOPs in JavaScript are Object Creation Pattern (Encapsulation) and Code Reuse Pattern (Inheritance).


Class Formation / Object Creation 

Class Formation / Object Creation : Object Literal

  • The most used pattern 
  • The good thing about this pattern is its simplicity. Just create an object right away and start using it.
Below example shows the formation of Student class and using its members. 
Other way to access the object values :

We can see in the above example that Student class has been formed. The class has many field values like firstName, lastName, sex and the method 'getFullName'.

Disadvantages of Object Literal way to form class/create objects:

  • It is explicit. You need to specify each and every property that the object has
  • Only suitable for the cases when you are to create one time object, singleton. Not good for creating multiple similar objects
  • If we need to create same type of object in other places, then we’ll end up copy-pasting the object’s methods, data and initialization.

Class Formation / Object Creation : Function returning an object / Factory function


              This pattern is an addition to the previous method (i.e. Object Literal). This encapsulates the object definition inside a function. This is found to be suitable for creating complex objects (as you don’t want the caller to know how it is built). Instead of creating the object literal directly , we return an object literal from the function. We may create the same type of object multiple times or in multiple places (we only need to invoke the function).

Below snap shot shows how to form class/create object using Factory function or Function returning an object way :


Creating more than one object and printing the values:


Disadvantages of Function Factory method:

It may perform slower than a constructor function in micro optimization benchmarks (The construction function method will be talked in the section below).

Class Formation / Object Creation : Constructor Function Method

                     This pattern is similar to the previous one i.e. Factory Function but some differences. We don’t return the object anymore. In fact the function itself doesn't return anything. We set the properties of object to be constructed using this. The function is called with new operator. This indicates that we have the function constructor via this keyword.

Below snap shot shows how to form class/create object using constructor function method:

Disadvantages of Constructor Function Method:

One have to remember to call the function with the new operator. In case we don’t do this , it will be treated as a normal/regular function. ‘this’ will be considered as the global object not just belonging to this function.


Class Formation / Object Creation : Constructor Function With Prototype Method
  
         A set of methods and properties can be defined in such a way so that they can be shared by the instances created using the constructor. All the instances will have a prototype which is the same object for all. This is considered to be the best choice in case we are creating multiple/many instances.

Below snap shot shows the class formation/object creation using Constructor function with prototype method :
                  

Class Formation / Object Creation : Object.Create Method

                        This pattern of object creation is supported in most of the modern browsers [ >IE 9]. We may create objects that have some prototype. This does the same what new does for the constructor function. This pattern is useful for creating multiple instances from a prototype. Its easier to understand. 

Below snap shot shows how to form the class/create objects using Object.Create method:



Constructors And Object Instances :

            JavaScript uses the special functions called as Constructor Functions to define objects and their features. They are found to be useful as there may be situations when you don’t know how many objects you are going to create. Constructors provide the means to create as many objects you need an effective way. When a new object instance is created using constructor – the functionalities are not copied over the new object (like classing OOPs languages) instead the functionalities are linked to via a reference called “prototype chain”.

Below snap shot shows the code which creates a constructor (obviously parameterized):




Class Element - Fields, Properties & Methods

                  We can achieve creating fields, properties and methods (both private and public) in the class. Private fields are those which cannot be accessed directly via the object instance. The public methods & properties can be accessed using the object instances.

Below snap shot shows a class having private fields, Properties and Methods:


We can see in the above example , only stdName (which is a public property) and publicMethodToShow(which is a public method) can be accessed through the object instance.

Calling private method from the public method of the class in order to use it outside the class using its object instance:


Inheritance :
Inheritance in JavaScript is achieved using prototyped call method

Let's use the derived class and call the methods :

The Output:

Extending JavaScript Math:

  • JavaScript Math class can be extended
  • Example:
    • We are going to extend the class the alter the method Max(). 
    • We are trying to re-write the method in such a way that it will compare max of  values supplied. This method has been altered in such a way that it would not take more that 3 values for comparison.



Hope you loved reading. Please post your comments and views if any.

Comments