Introduction
Few days back I was trying to port my Android Game Development Kit (GDK) into HTML5 (JavaScript based GDK), for that I got a chance to explore Classes (object oriented) in JavaScript. Please note that I am not an expert of JavaScript, and in this tutorial I have tried to cover all the searches and efforts that I put to get my JavaScript code running in Object Oriented (Classes).
To Keep this tutorial simple I will use very simple example instead of complex game related domain ideas. and will not discuss what OOP is and how and where classes are used in greater or expert level details. I will assume that readers have the knowledge of object oriented programming (using classes in code).
In real life we see different animals. All the animals have few characteristics, habits and actions, and whenever we have to handle such an information for more than one (repeatedly) we think in terms of a Class in computer software programming. Similarly there is another thing which drive us to use class and that is grouping the similar actions and characteristics in one place, again OOP Class is our best shot.
We know that most of the animals have names(Puppy, ScubyDuby), type(Cat, Dog, Lion, Elephant, Tiger etc), color, age etc. so we will group all these information into one Class (Class is basic template or blueprint for some thing)
Animal{ name type color age }
Now for each different animal we will create an object (Instantiation of object of the blueprint/template (i.e. Class)). An object of type Animal(Class). and then we will populate the attributes with the required information.
examples are as follows.
Animal { name: "Tango" type: "Lion" color: "Yellow" age: "2 years" } |
Animal { name: "Suzi" type: "Elephant" color: "Black" age: "4 years" } |
We can see that we have grouped and encapsulated relevant information of a particular real life object(the one we see in real world). and now we can store and manipulate this information easily.
before jumping to actual class, lets compare ordinary way and using classes.
//populating variables var animal_1_name = "Tango"; var animal_1_type = "Lion"; var animal_1_color = "Yellow"; var animal_1_age = "2 years"; var animal_2_name = "Suzi"; var animal_2_type = "Elephant"; var animal_2_color = "Black"; var animal_2_age = "5 years"; //printing this information var str = "** Here is detail of first animal **\n"; str += "Name: "+ animal_1_name +"\n"; str += "Type: "+ animal_1_type +"\n"; str += "Color: "+ animal_1_color +"\n"; str += "Age: "+ animal_1_age +"\n"; str += "** Here is detail of Second animal **\n"; str += "Name: "+ animal_2_name +"\n"; str += "Type: "+ animal_2_type +"\n"; str += "Color: "+ animal_2_color +"\n"; str += "Age: "+ animal_2_age +"\n"; alert(str);
We can see that there is no such boundary or nothing the code is pretty much messed up and more lines of code. which makes it less manageable ( Consider an example in which we require the information of 10 different animals)
Similarly OOP based code
var animal_1 = new Animal("Tango", "Lion", "Yellow", "2 Years"); var animal_2 = new Animal("Suzi", "Elephant", "Black", "5 Years"); alert(animal_1.getDetail()); alert(animal_2.getDetail());
We can see our code is very nice and clean and we only concentrate on our logic in main script instead of handling different variables or related information. Similarly we are reusing functionality. likegetDetail() will format string as we want. moreover if in the future we want to change some formatting or want to add an extra field, we don’t have to change code for 10 different animals and resolving the code changes. We will only make a change in relevant class that will be shared(depicted) everywhere, our main script code will be almost intact.
That’s it, I will not go in further object oriented details
Now lets get straight to JavaScript class.
2. JavaScript Class
Every function in JavaScript can behave as a class, and that’s how we define classes in JavaScript.
//class declaration + constructor of class function Animal( name , age ){ this.name = name; this.age = age; } //class attributes definitions Animal.prototype.name = "Animal"; Animal.prototype.age = 0; //class functions declaration and body Animal.prototype.getDetail = function(){ return "Name: " + this.name + "\n" +"Age: "+this.age + "\n"; }
In example above we have defined a class(Animal) that have only 2 attributes (name and age) and only one method/function (getDetail())
2.1 Implementation
var a = new Animal("Kitty", 2); //alert complete detail alert(a.getDetail()); //access an attribute of a class (you can also write getter and setter function) a.name = "Mimi"; //alert complete detail alert(a.getDetail());
2.2 Access Modifier in JavaScript
2.2.1 Public
In our Animal class we have created 2 variables name and age. both are public variable as we have defined them with following line of code.
Animal.prototype.name = "Animal"; Animal.prototype.age = 0; //these are accessible with this with in the class methods this.name //and can be accessed out of the class by using its instantiated object objAnimal.name
In simple terms where ever we use this operator with a variable it mean its a public variable.
this.name = name; this.age = age; return "Name: " + this.name + "\n" +"Age: "+this.age + "\n";
2.2.2 Private
In order to have private variables we have to trick JavaScript in following way.
function Human() { //public this.name = "Mazhar Hassan"; //private var _age = 5; //Getter/Setter to access private variables //Please note these getter setter themselves will be public this.getAge = function(){ return _age; }; this.setAge = function(age){ _age = age; }; } Human.prototype.name = ""; Human.prototype.getName = function() { return this.name; } //Now we can access this private variable var h = new Human(); alert(h.getAge()); h.setAge(23); alert(h.getAge());
2.3 Static variable in JavaScript
Again there is no reserve word for creating static variables, its the way how we access that variable. These are private variables we defined in previous example, only difference is getter and setter methods.
function Human() { //public this.name = "Mazhar Hassan"; //private var _age = 5; //Getter/Setter to access private variables //Please note these getter setter themselves will be public this.getAge = function(){ return _age; }; this.setAge = function(age){ _age = age; }; //private static variable var _password = ""; //public getter/setter for static variable Human.prototype.setPassword = function( password ) { _password = password; } Human.prototype.getPassword = function() { return _password; } } Human.prototype.name = ""; Human.prototype.getName = function() { return this.name; } //IMPLEMENTATION -------------------------------------------------- var h1 = new Human(); var h2 = new Human(); h1.setPassword("xyz"); h2.setPassword("abc"); alert(h1.getPassword()+" = "+h2.getPassword()); //will print "abc = abc"
3. Inheritance in JavaScript
Concept of inheritance in JavaScript is same like few other languages. As we already know in order to create a class in JavaScript we have to define a function that can behave as a class. lets define a Dogclass, that will inherit Animal class.
//Dog class inherits Animal Class Dog.prototype = new Animal(); //Dog Class + constructor function Dog( name , age){ this.name = name; this.age = age } //speak function of Dog Dog.prototype.Speak = function(){ alert("waoo waoo"); }
3.1 Implementation
The implementation is pretty much same we are still able to access function and attributes of parent class(Animal) using child class(Dog).
var d = new Dog("Skubby", 2); alert(d.getDetail());
The Dog class we previously created is inheriting Animal class and have introduced a new function called speak hence we can add more functions and attributes when ever we need to extend any functionality.
3.2 Calling Parent Constructor
In the constructor of child class we can make a call to parent constructor. our previous constructor of child class looks like as follows.
function Dog( name , age){ this.name = name; this.age = age }
We simply replace it by calling parent constructor.
function Dog( name , age){ Animal.call(this, name, age); }
and following code will return the same result as were before.
var d = new Dog("Skubby", 2); alert(d.getDetail());
3.3 Overriding a method/function of parent class (Method Overriding)
Now we will override method of a parent class in child class.
//Dog class inherits Animal Class Dog.prototype = new Animal(); //Dog Class + constructor function Dog( name , age){ Animal.call(this, name, age); } //speak function of Dog Dog.prototype.Speek = function(){ alert("waoo waoo"); } //Overriding method Dog.prototype.getDetail = function() { return "--- This is a DOG object ---\n"; }
3.4 Calling function of parent class
Syntax
<parent-class-name>.prototype.<method-name>.call(this <,method-arguments>); Example: Animal.prototype.getDetail.call( this ); //Dog class inherits Animal Class Dog.prototype = new Animal(); //Dog Class + constructor function Dog( name , age){ Animal.call(this, name, age); } //speak function of Dog Dog.prototype.Speek = function(){ alert("waoo waoo"); } //Overriding method Dog.prototype.getDetail = function() { return "--- This a DOG object ---\n" + Animal.prototype.getDetail.call( this ); }
3.5 Multiple Inherence in JavaScript
Simple answer to multiple inheritance is, JavaScript does not support multiple inheritance just like Java programming language. We know that in order to inherit a class we use following code
Dog.prototype = new Animal();
If you think by Inheriting another class in similar way will work, then you are wrong it will actually replace the inheritance
//Dog is inheriting Animal class Dog.prototype = new Animal(); //Dog is NOW inheriting Bird class Dog.prototype = new Bird(); //Previous declaration is overwritten
However there are few workarounds to get the feel of multiple inheritance but that is not actually real inheritance. you can using cloning technique to clone the functions of any other parent class to your child class. however that is not in the scope of this tutorial.
Here are few links that have provided few ways to achive mulitiple inheritence in different ways.
1 –Multiple Inheritance in Javascript
2 –Experimenting With Multiple Class Inheritance In Javascript
3 –Implementing Multiple Inheritance in Javascript
4 –Multiple inheritance in javascript : StackOverflow : Read the last comment by MooGoo, The simplest way to understanding the trick of multiple inheritence.
5 –Classical Inheritance in JavaScript : I have strong recommendation to read this link, it explain different types/styles of Inheritance as well defining class in JavaScript