Advantage of adding members to a class using "prototype" (in JavaScript)

by Jagadish Pulakhandam on 9/7/2012 7:45:49 AM
Rated 0 from 0 votes
Brief: Demonstrates advantage on adding members to a class using "prototype"
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

Attaches Source Code/Video demonstrates the following:
  • Create a class (function constructor) and instantiate a couple of objects using JavaScript
  • Adding methods as part of class during its own definition
  • Adding new methods to an existing class using "prototype"
  • Test the advantage of using "prototype" in JavaScript
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: advantage of adding methods to prototype
08. 
09.        //create function
10.        var Emp = function (vEmpno, vEname, vSal) {
11.            this.Empno = vEmpno;
12.            this.Ename = vEname;
13.            this.Sal = vSal;
14. 
15.            //method added normally (a copy will be created for every instance)
16.            this.ShowAnnSal = function () {
17.                alert("Annual Salary: " + (this.Sal * 12).toString());
18.            }
19.        };
20. 
21.        //method added through prototype (same copy will be shared by all instances)
22.        Emp.prototype.ShowQuarterSal = function () {
23.            alert("Quarter Salary: " + (this.Sal * 3).toString());
24.        }
25. 
26.        //create objects
27.        var oEmp1 = new Emp(1001, "Jag", 3400);
28.        var oEmp2 = new Emp(1002, "Chat", 4400);
29. 
30.        //demonstrating the difference
31.        alert(oEmp1.ShowAnnSal == oEmp2.ShowAnnSal); //false - each object maintains a copy of method (more memory)
32.        alert(oEmp1.ShowQuarterSal == oEmp2.ShowQuarterSal); //true - all objects share same method (less memory)
33. 
34. 
35.    </script>
36.</head>
37.<body>
38. 
39.</body>
40.</html>



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


Discussion
No comments yet!