How to implement inheritance in JavaScript using JavaScript's "Prototype"

by Jagadish Pulakhandam on 9/20/2012 10:26:16 AM
Rated 0 from 0 votes
Brief: Demonstrates on implementing a simple inheritance using "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:
  • How to implement Simple Inheritance in JavaScript using "prototype" 
  • How to create instances of child class in JavaScript
  • How to access members from child object
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: Simple Inheritance using Prototype (recommended way)
08. 
09.        //create parent class
10.        var Person = function () {
11.            this.Id = 0;
12.            this.Name = "";
13.        };
14. 
15.        //create new class
16.        var Emp = function () {
17.            this.OfficeEmail = "";
18.        };
19. 
20.        //make Emp class as a child of Person class
21.        Emp.prototype = new Person();
22.        Emp.prototype.constructor = Emp; //Otherwise instances of Emp would have a constructor of Person
23. 
24.        //create instance of child class
25.        var oEmp = new Emp(); //using Child's constructor
26. 
27. 
28.        //test child/parent properties for their existence.
29.        alert(oEmp.hasOwnProperty('OfficeEmail'));//true
30.        alert(oEmp.hasOwnProperty('Id'));//false
31.        alert(oEmp.hasOwnProperty('Name'));//false
32. 
33.        alert("Id" in oEmp); //true - inherited property
34.        alert("Name" in oEmp); //true - inherited property
35.        alert("OfficeEmail" in oEmp); //true - direct property
36. 
37.        oEmp.Id = 1001;
38.        oEmp.Name = "Jag";
39.        oEmp.OfficeEmail = "jag@jag.com";
40. 
41.        alert(oEmp.Id);
42.    </script>
43.</head>
44.<body>
45. 
46.</body>
47.</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