Tuesday 3 June 2014

Introduction to Object Oriented Javascript

Introduction
Many programming languages uses class based object oriented based paradigm, However, JavaScript uses prototype based paradigm. Let's get more deeper into that....

JavaScript was simply used as a scripting language which was mainly used by web-designers to do simple dynamic tricks on web pages. With time the JavaScript has evolve as one of the important full featured programming language to built rich Internet application rather than just doing simple tricks on the website.

                                    Object Oriented JavaScript
JavaScript uses class-less based object oriented paradigm which is also known as prototype based object oriented paradigm.
In prototype based object oriented paradigm, rather than defining set of class templates from which the objects are created, the objects are declared as they are needed.

                                                Advantage 
One of the major advantage of prototype based OOP paradigm is that the objects can be modified at runtime. This means that the definition structure of the object is not strict as the classes are not defined.

                                                  Example
Let us see an example of object oriented paradigm, A function serves as an object prototype. To create an instance of this object new keyword is used.



1
2
3
function Car() { }
var myCar = new Car();
console.log(myCar);

Here the function Car() serves as an object and myCar is an instance of Car().
The output of the above code is object{}

To see a complete example of the same Following is the code :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
<head>
    <title>Learning Dojo</title>
    <script src="dojoroot/dojo/dojo.js">
</script>

</head>
<body>
<h1>Learning Dojo</h1>
<div>Object oriented javascript</div>
<ul id="list">
    <li>It is class-less based object oriented paradigm</li>
    <li>Allow to modify object at runtime</li>
    <li>class template need not to be defined</li>
</ul>
<script>
    function Car() { } //Here Car function serves as an object
    var myCar = new Car(); // myCar is an instance of Car object
    alert(myCar); // This will show the output as object in the alert-box
    
</script>
</body>
</html>


After running the above code in the browser we get the following output: