Creating Classes in Javascript

This example demonstrates how to create a pseudo class in javascript. The javascript class is actually an empty function and you can assign attributes to it at runtime. This is very useful as it allows the encapsulation of related data and helps to make code neat.

Let us have a look at the example. It is self explanatory. We create two instances of MyClass, a and b, but assign different attributes to them.
 1. function MyClass(){}
 2. 
 3. a = new MyClass();
 4. a.text = "The sum is "
 5. a.num1 = 10;
 6. a.num2 = 20;
 7. 
 8. b = new MyClass();
 9. b.firstname = "Jason";
10. b.lastname = "Bourne";
11. 
12. function X(p){
13.     if(p.num1!=null)
14.         alert(p.text +(p.num1 + p.num2));
15.     else
16.         alert(p.firstname+" "+p.lastname);    
17. }
18. 
19. X(a);
20. X(b);
Hide line numbers