JavaScript OOP Model

Sul Aga photo
0
Last Updated
Jul 25, 2015
Tags
Source Code

Introduction

When using JavaScript for the first time you probably didn’t think of it as an Object Oriented language; however it appears as a structured language with basic programming structures like conditions and loop statements. JavaScript is an Object Oriented language however the object’s notation is different from the one in C# or JAVA. In JavaScript you don’t get an object by instantiating (another word for creating) it from a class but by manipulating special, native object called the prototype

JavaScript OOP Model

The JavaScript OOP model revolved around 3 major elements and these elements are prototype object, arrays and functions. The JavaScript object can be seen as a collection of key/value pair (dictionary). You can create an object in JavaScript using the following syntax.

var myObj = new Object();

or

myObj = {};

To add a property to the new created object we can just access that property. If it exist, the value will be overwritten. If it doesn't exist then the property will be created and assigned the value specified.

myObj.Name = "object name";

You access the property using the same syntax; for example this line will display "object name" in an alert message

alert(myObj.Name);

In JavaScript array is an indexed collection that can contain different types. Unlike arrays in .NET, in JavaScript you don’t need to specify the size of the array. Arrays in JavaScript resembles generics in .NET in that you don’t need to specify the size when creating the collection and it can contain different types. Here is how you create arrays in JavaScript.

var myArray = new Array();

or

var myArray = [];

To access the elements in the array you specify the index (position) of that element in the array. In this example we are creating an array of 3 elemnts and we are showing the value of the second element in an alert message.

var myArray = new Array(); 
myArray[0] = "string value";
myArray[1] = 2; 
myArray[3] = true; 
alert(myArray[1]);

As I specified earlier that the object in JavaScript is nothing but a collection of key/value then you can set the properties for the object in the same way as you did for the array, so these statements are perfectly correct.

var myObj = {}; 
myObj['title'] = "this is my title";
myObj['name'] = "this is my name";
alert(myObj.title); 
alert(myObj.['title']);

JavaScript treats function as objects which mean that functions in JavaScript can be assigned to a variable or even returned by other function. Have a look at the code below

var myObj = {}; 
myObj.getTitle = function() { return "this is my title"; } 
alert(myObj.getTitle());

As you can see from the code above, the getTitle will store a function and as such a call to getTitle will result in calling the function that is assigned to it.

Creating Objects

As stated above, JavaScript treats functions as objects and as such you can use this feature to create a constructor for your objects. Consider this constructor for a Car object.

function Car() { 
this._color = ''; 
this._type = ''; }

Now to create a Car object you need to use the new word with the ‘class’ name which is Car to create an object of type Car that has two properties namely _color and _type.

var redCar = new Car();

One might ask how do we define other functionalities for the class i.e. methods, setters and getters. The answer is the prototype object. The content of this special object will be shared among all instances of this class. Think of it as static field. Properties setters and getters as well as methods will go in the prototype object. You can add methods to the constructor it self but this will degrade performance as every instance will hold a copy of the same structure but if you define methods in the prototype object then these methods will be shared among all objects of that type. Consider this prototype for the Car class

Car.prototype = { 
  drive: function () {alert ("driving" + this._color + " car!");}, 
  goTo: function(dir) { alert("Going " + dir ); } 
}

In this prototype we are defining two methods namely drive and goTo. The interesting part about the drive is that it is accessing the _color field. As stated earlier, what is defined in the constructor is not shared among the objects i.e. these fields are copied in every instance of the Car class. As such accessing these fields will provide the values specified to the object which is calling the prototype methods. Consider this example to further illustrate this concept.

var redCar = new Car(); 
redCar._color = "red";
redCar.drive();
redCar.goTo("right"); 
var blueCar = new Car(); 
blueCar._color = "blue"; 
blueCar.drive();
blueCar.goTo("left");

In this code snippet, both redCar and blueCar are objects of type Car. They both share the same methods but every instance has its own values for the properties defined in the constructor.

Inheritance

Inheritance can be implemented in JavaScript but the implementation will be different than OOP languages like C#. In C# for example the inheritance is based on the class as a building block for inheritance i.e. the child class will inherit the parent class’s properties and methods. In JavaScript, the inheritance building block is the prototype object. By assigning the prototype object of the parent class to the child class, the child class will inherit all the methods defined in the parent’s prototype object. To inherit the properties of the parent class then you need to call the parent class constructor from the child class constructor. Have a look at this example for inheriting the Car object declared previously.

var SportCar = function () { 
    Car.call(this); 
    this._engSize = ''; 
 } 
SportCar.prototype = new Car(); 
SportCar.prototype.drive = function(){
    alert ("driving " + this._color + " car with engine size of " 
            + this._engSize); 
 }

In the code listing above we first call the parent constructor to inherit the properties (fields) of the parent class. Then we call the prototype of the parent class to inherit the methods. Note also how we were able to override the drive method defined in the parent class. Now calling this method on a SportCar instance will call the overridden method. The parent methods will be invoked if you don’t override them in the child class.

Summary

JavaScript is an OOP language however the concept of object is different from the other OOP languages like C#. The building blocks for JavaScript OOP are prototype object, arrays and functions. JavaScript treats function as objects. Creating an object in JavaScript includes creating a constructor which will include all the object’s fields. The object’s methods will go in the prototype object. The content of the prototype object will be shared among all the instances. Inheritance can be implemented in JavaScript by assigning the prototype object of the parent class to the prototype of the child class.

Comments