Introducing "Prototype" in JavaScript

by Jagadish Pulakhandam on 9/7/2012 7:29:25 AM
Rated 0 from 0 votes
Brief: A simple example to understand "Prototype" in JavaScript
Posted to: Advanced JavaScript Programming/Development tutorials/videos- Object Oriented Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached Source Code/Video demonstrates the following:
  • Create definition of a class in JavaScript and instantiate a couple of objects out of it
  • Add a new method (or member) to the definition of the class using "prototype"
  • Check to see if the newly added method is available (automatically) in all objects instantiated previously
Source Code:

01.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
03.<html>
04.<head>
05.    <title></title>
06.    <script type="text/javascript">
07.        //DEMO: modifying the definition of a function using "prototype"
08. 
09.        //create a class
10.        var Emp = function(vEmpno, vEname, vSal) {
11.            this.Empno = vEmpno;
12.            this.Ename = vEname;
13.            this.Sal = vSal;
14.        };
15. 
16.        //display properties (of an object) using a function
17.        function dispEmp(o){
18.            if (o.AnnSal) //check to see if property exists
19.                alert(o.Ename + ' earns ' + o.AnnSal().toString());
20.            else
21.                alert("AnnSal could not be calculated for " + o.Ename);
22.        }
23. 
24.        //create objects
25.        var oEmp1 = new Emp(1001, "Jag", 5400),
26.                oEmp2 = new Emp(1002, "Chat", 6400);
27. 
28.        //Add a new method to the definition/skeleton of "Emp" (class) using "prototype" (not to oEmp1 or oEmp2)
29.        //Adding using "prototype" would automatically get reflected to all of its instances (instantaneously)
30.        //Also, adding using "prototype" maintains only one copy in memory (vs. each copy for every instance when added manually)
31.        Emp.prototype.AnnSal = function() {
32.            return this.Sal * 12;
33.        };
34. 
35.        //display employee details (AnnSal will be available to all objects automatically)
36.        dispEmp(oEmp1); //displays annual salary of oEmp1
37.        dispEmp(oEmp2); //displays annual salary of oEmp2
38. 
39.    </script>
40.</head>
41.<body>
42. 
43.</body>
44.</html>


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following