Constructors in JavaScript

A constructor is a function that instantiates a new object. This is done only when memory has been allocated for it. We create a new object like this:

var obj=new Object();

var obj={};

var n=new Number(10); // Here we create a Number Object
 
We can also create a custom constructor function like this:
 

function Calc(a,b,Total)

{

  this.a=a;

  this.b=b;

  this.Total=Total;

}

Now we can easily invoke the Calc constructor like this:
 

var c1=new Calc(20,10,0);

Prototype

A Prototype is a property of a function in JavaScript. So when we invoke the Constructor to create an object, all the properties of the constructor's prototype are available to the newly created object.

Now we will use an example in which we will set a method (add()) on the prototype. Here we create multiple objects of Calc, these objects can access the add() function
as in the following.

Example 1

<head id="Head1" runat="server">

<title>Untitled Page</title>

<script language="javascript" type="text/javascript">

    function Calc(a, b, Total) {

        this.a = a;

        this.b = b;

        this.Total = Total;

        Calc.prototype.add = function add() {

            this.Total = this.a + this.b;

            return this.Total;

        }

    }

    var c1 = new Calc(20, 10, 0);

    alert(c1.add());

   

    </script>

</head>

<body onload="Calc(x,y,t)">

    <form id="form2" runat="server">

    <div>   

    </div>

    </form>

</body>

Here we create a function add() , using the function we add the two values (a,b) and assign the total (Total) and return the value of Total.

Then, we invoke the Calc Constructor like this:
 

var c1=new Calc(20,10,0);

alert(c1.add());
 
Here we assign the value: a=20,b=10, Total=0.

So the output will be:

protype in javascript

In this program we use Prototype like this:

Calc.prototype.add=function add(){

Now we create another Calc() object like this:
 

var c2=new Calc(30,15,0);

alert(c2.add());

And the output is:

Prototype

Example 2

<script language="javascript" type="text/javascript">

        function Student(name) {

        this.name = name;

    }

    Student.prototype.Total = function () { return 300; };

    Student.prototype.Total1 = 200;

    var theStudent = new Student('Mahak');

    alert(theStudent.Total());

    alert(theStudent.Total1);

    alert(theStudent.name);

</script>

The output will be:

Prototype result

Up Next
    Ebook Download
    View all
    Learn
    View all