Friday, November 29, 2013

Constructors in JavaScript

A constructor is a function, which is used to instantiate 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 custom constructor functions 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 in order to create an object, all the properties of the constructor’s prototype are available to the newly created object.
Now we will take 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 like this:

<head 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="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>


Here we create a function add() , with the help of the function we add the two values (a,b) and assign the total in  (Total) and return the value of Total.
After that, 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:



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:



Ex 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:






No comments:

Post a Comment