December 3, 2014

122 Views

Back to Basics – JavaScript Classes

Sometime ago, I was searching on the Internet for JavaScript classes. I have been asked about this at every interview, in various companies and in myriad situations. I could never give a conclusive answer and could only make some basic statements concerning it. Realizing this, I began searching for classes on the Internet; spent a couple of hours but did not really get anything satisfactory. Most of the Internet pages that talked about JavaScript classes were quite vague and were not able to satisfy my desire to learn.  So, I thought of digging down some more to try and understand the concept of classes and how exactly they could help a JavaScript developer or even a Web developer, as queries around classes, constructors and prototypes have always been asked of me during most of my interviews.

Upon understanding the concept of classes and constructors, I realized that this is something we see and work with on a day to day basis.  All I had to do to get around these concepts was to start viewing everything around me as classes and their inheritance or extensions. In doing so, my rich experience with UI development helped.

I’d like to share a simple example that we find in day to day life.

Most of us love and care for animals. We even plan holidays around zoo or national park visits, and some people even have pets at home.

I’d like to use common animals for this example, say, a cow and a sheep.

Both of them are in the same category or class – i.e. Animals. But, they have unique properties. Cows give milk and sheep have bows (Bows are used in the creation of wool). So these animals have different properties which are harvested differently – milkman to milk the cows and a shearer for the sheep.

Let me separate these two animals’ properties here with the help of a script to understand this better.     

Let’s create a JavaScript code:

function myAnimal(animalName,milk,bows){ // I have created the function myAnimal and set the parameter Name and it’s possible properties

this.animalName      =      animalName;   // this parameter for Animal Name

this.milk            =       milk;         // this parameter for Milk

this.bows            =      bows;         // this parameter for Bows

}                                                                              

The above code is a function where I have declared various parameters from the different objects.

The script below will validate the parameter for a milk providing animal:

I am going to create a new object constructor from the above function myAnimal using a NEW keyword.

myMilkAnimal = new myAnimal() { // it is called an object constructor, it constructs objects from a blueprint from a FUNCTION myAnimal() using NEW keyword.

myMilkAnimal.name    = cow ; // setting the parameter for Animal Name

myMilkAnimal.milk    = true ; // setting the parameter for Animal Property

myMilkAnimal.bows    = false ; // setting the parameter for Animal Property

}

Here’s  a short script for this:

myMilkAnimal = new myAnimal( " Cow " , true, false );

myMilkAnimal is a new blueprint object from the above function myAnimal(). I pass the actual value from here. It means the Animal’s name is a Cow and its properties are milk=yes and bows=no

The above script is rendered with the following value:  Milk Provider [Cow]

The script below will validate the parameter for a Bow providing animal:

myBowsAnimal = new myAnimal( " Sheep " , false, true ); // it is called an object constructor, it constructs objects from a blueprint from a FUNCTION myAnimal() using NEW keyword same as above.

myMilkAnimal.name    = sheep ; // setting the parameter for Animal Name same as above

myMilkAnimal.milk    = false ; // setting the parameter for Animal Property same as above

myMilkAnimal.bows    = true ; // setting the parameter for Animal Property same as above

The above script is rendered with the following value:  Bow Provider [Sheep]

The above script will give us: A bow providing animal’s name is sheep and it provides bows but no milk.

Now, where is the class?

We created the function and then a constructor object. Now we need to dig further to understand about the class.

With the new constructor object myMilkAnimal, I have all the parameter sets and just need to validate this and display it on the browser. I will be using conditional statements here to validate the above parameters and get the expected results.

To display the output, I used a JavaScript method called “document.write” which is one of the easiest ways to display data on a browser.

document.write

( ' Milk/Bows provider Animal name ' + animalName + ' and it provides ' + ( milk ? ' yes ' : ' no ' ) + ' and bows ' + ( bows ? ' yes ' : ' no ' ) + '  <BR> ' ) ;

JavaScript doesn't have a keyword specific to class; functions can be used to sort of simulate classes. In JavaScript, everything is an object, and when it comes to inheritance, objects inherit from objects, not classes from classes.

From the above example, I get flexibility, modularity and re-usability by created objects, functions, properties and methods to get the data. E.g., Animal category from the above example and its class properties can be accessed by class objects or invoked class methods.

Please run this markup on your browser and you will see the results:

<html>

<head>

<title>My Animals</title>

<script> 

                function myAnimal ( animalName , milk , bows ) {

                                this.animalName  = animalName;

                                this.milk        = milk;

                                this.bows        = bows;

                }

                myBowsAnimal = new myAnimal( " Sheep " , false, true );

                myMilkAnimal = new myAnimal( " Cow " , true, false );     

                document.write( ' My animal ' + myBowsAnimal.animalName + ' gives me Milk ' + ( myBowsAnimal.milk ? ' yes ' : ' no ' ) + ' but Bows ' + ( myBowsAnimal.bows ? ' yes ' : ' no ' ) + ' <BR> ' );

                document.write( ' My animal ' + myMilkAnimal.animalName + ' gives me Milk ' + ( myMilkAnimal.milk ? ' yes ' : ' no ' ) + ' but Bows ' + ( myMilkAnimal.bows ? ' yes ' : ' no ' ) + ' <BR> ' );

 </script>

</head>

<body>

</body>

</html>