How to override base class methods in JavaScript (when used with "prototype")

by Jagadish Pulakhandam on 9/24/2012 4:29:02 PM
Rated 0 from 0 votes
Brief: Demonstrates on overriding methods using JavaScript when base class is defined 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

Attached source code/video demonstrates the following:
  • How to create parent/child classes (function constructors) in JavaScript (using "prototype")
  • How to declare methods in parent class and override the same in child class
  • How to create instances/objects of parent/child classes and access the overridden methods
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: Overriding methods using prototype
08. 
09.        //create parent class
10.        var Person = function (vId, vName) {
11.            this.Id = vId;
12.            this.Name = vName;
13.        };
14. 
15.        Person.prototype.Display = function () {
16.            alert("Id=" + this.Id.toString() +
17.                    ", Name=" + this.Name);
18.        }
19. 
20.        //create new class
21.        var Emp = function (vId, vName, vOfficeMail) {
22.            if (arguments.length < 3) return;
23.            Person.call(this, vId, vName)
24.            this.OfficeEmail = vOfficeMail;
25.        };
26. 
27.        //make Emp class as a child of Person class
28.        Emp.prototype = new Person();
29.        Emp.prototype.constructor = Emp;
30.        //overriding method
31.        Emp.prototype.Display = function () {
32.            alert("Id=" + this.Id.toString() +
33.                    ", Name=" + this.Name +
34.                    ", OfficeMail=" + this.OfficeEmail);
35.        }
36. 
37.        //create instance of child class
38.        var oEmp = new Emp(1001, "Jag", "a@a.com"); //using Child's constructor
39.        //call display method in child class
40.        oEmp.Display();
41. 
42.        //create instance of parent class
43.        var oPerson = new Person(1002, "Chat"); //using Parent's constructor
44.        //call display method in parent class
45.        oPerson.Display();
46. 
47. 
48.    </script>
49.</head>
50.<body>
51. 
52.</body>
53.</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