How to define a class (using function constructor) in JavaScript and instantiate it

by Jagadish Pulakhandam on 8/14/2012 2:41:53 PM
Rated 0 from 0 votes
Brief: Demonstrates on defining classes (using function constructors) and instantiating them using 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 define a class like structure using function constructors in JavaScript
  • How to instantiate a function constructor (create an object or instance based on the class defined)
  • How to access its properties (using object.property notation)
  • How to access all properties of an object (instance) using "for" loop in JavaScript
NOTE:  JavaScript does not have built-in support for "pure" classes.  We can achieve similar to "classes" using "function constructors"

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: using constructors functions to define objects
08. 
09.        //defining a (class/function) constructor accepting 4 parameters
10.        function Emp(vEmpno, vEname, vSal, vDeptno) {
11.            this.Empno = vEmpno;
12.            this.Ename = vEname;
13.            this.Sal = vSal;
14.            this.Deptno = vDeptno;
15.        }
16. 
17.        //creating object
18.        var oEmp = new Emp(1001, "Jag", 5400, 10); //calling the constructor
19. 
20.        //accessing members of an object
21.        alert(oEmp.Empno.toString() + ", " +
22.                oEmp.Ename + ", " +
23.                oEmp.Sal.toString() + ", " +
24.                oEmp.Deptno.toString()
25.        );
26. 
27.        //parsing all members using a loop
28.        for (var p in oEmp) {
29.            alert(p + ' = ' + oEmp[p]);
30.        }
31. 
32. 
33.    </script>
34.</head>
35.<body>
36. 
37.</body>
38.</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