Creating classes with Javascript

Javascript is a prototype-based language rather than a class-based language (e.g. Java). For an explanation of the difference, see Mozilla's comparison of class-based and prototype-based languages.

In short, in a class-based language, objects are created by instantiating classes. The classes' list of properties and methods cannot be altered (e.g. added to) at runtime. A prototype-based language does not have the notion of a class. Everything is an object. A prototype-based object can have its list of properties and methods modified during runtime.

The examples below show how to create a class in Javascript. First we define a function that will behave as our constructor. Then we extend that function's prototype to include further functions that will behave as the class' methods. Note the use of the "this" keyword to refer to the prototype of the current object.

JAVASCRIPT:
  1. //This is our constructor
  2. function SuperHero(heroID, p1, p2, p3) {
  3.     this.heroID = heroID;
  4.     this.name = null;
  5.    
  6.     this.power_1 = p1;
  7.     this.power_2 = p2;
  8.     this.power_3 = p3;
  9.    
  10.     this.power_ultimate = p1 + p2 + p3;
  11. }
  12.  
  13. //Now add some methods to the class
  14. SuperHero.prototype.getPower1 = function() {
  15.     return this.power_1;
  16. }
  17.  
  18. SuperHero.prototype.losePowers = function() {
  19.     this.power_1 = null;
  20.     this.power_2 = null;
  21.     this.power_3 = null;
  22. }
  23.  
  24. SuperHero.prototype.setName = function(name) {
  25.     this.name = name;
  26. }
  27.  
  28. SuperHero.prototype.alertProfile = function() {
  29.     var str = 'Hero Profile:\n' +
  30.               'Name: ' + this.name + '\n' +
  31.               'Name: ' + this.name + '\n' +
  32.               'Name: ' + this.name + '\n' +
  33.               'Name: ' + this.name + '\n' +
  34. }

And now we have a simple class with a few simple properties and methods. Usage of the class would be something like:

JAVASCRIPT:
  1. var Superman = new SuperHero(2331, 'Flight', 'Speed', 'Strength');
  2. Superman.setName('Superman: Man of Steel');
  3. var power_1  = Superman.getPower1();
  4.  
  5. if (kryptonite) {
  6.     Superman.losePowers();
  7. }
  8.  
  9. Superman.alertProfile();

Leave a Reply

Your email address will not be published. Required fields are marked *

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>