Built.io Blog

An Introduction to Objects, Constructors, and Prototypes in Javascript

,

Before discussing the basics of object, prototype, and constructor in Javascript, I would like to share some general points which I believe are important before one codes in Javascript.

It’s important to follow a pattern in your coding style. Many people follow their own coding patterns, some follow pre-defined coding patterns, and others simply avoid coding patterns completely. Pattern coding is good because it allows you to maintain readable, manageable, and most importantly, debugable code.

I personally advocate that you write your code following the MVC framework but if you’re following a pattern, I’ll be happy. Let the fun begin…

Objects

As we know Javascript is an Object Oriented Programming (OOP) language and one can take advantage of the object concept (write once use many times). Basically, an object is a collection of properties which can be anything (string, int, another object or function). If an object has a function as a property, we refer to this function as a method. One can easily set and get the properties of an object (both for built-in and custom ones) if the object provides the appropriate methods to do so.

A common built-in object I use often in Javascript is the document object. For example, we use the title property to change the title of a webpage: document.title="Hello world";. Similarly, to get the title of a webpage we can use var title=document.title;.

In a document object there are many other useful methods. For example, we can use the write method, document.write("Hello world"); to add anything to a webpage on the fly.

Similarly to built-in objects, we can always create custom objects. Usually every function in JavaScript is in fact an object itself.

For example, lets create an object named page to do some task related to a document object:

<code>function page_cons(){
  this.$id=function(args){
    return document.getElementById(args);
  }
  this.$tag=function(tag){
    return document.getElementsByTagName(tag);
  }
}
var page=new page_cons();
page.$tag('title')[0].innerHTML="hello world";
</code>

In the above example we have created an object constructor to create a custom object which can complete two tasks:

  1. Get the element by id
  2. Get the element by tag name

After creating the object, we used $tag method (which we defined in page_cons constructor function to get the element by tag name) to change the title of the webpage.

Lets follow another example to help clear things up:

<code>function MyObject(name){
  this.name=name||'no-name';
  this.getName=function(){
    return this.name;
  }
}
var boy=new MyObject('pradeep');
boy.getName() // return pradeep;
boy.name='ravi' // will set name variable as ravi
</code>

In the above code we used the MyObject function to wrap another function and make a constructor function (which we will discuss later) to instantiate the boy object and use it to access object variable and methods (like classes in Java).

In Javascript, there is no native support for private or public member type, but with a bit of coding logic we can achieve it just like in this object.

To use a private variable in your object we can declare the variable with var to make it make it inaccessible outside the scope of the object. For example:

<code>function MyObject(name){
var name='no-name';
 this.getName=function(){
    return name;
 }
 this.setName=function(args){
   name=args||'';
 }
}
var boy =new MyObject('pradeep');
boy.getName() // return pradeep;
boy.name='ravi' // will do nothing
</code>

In the above code, we cannot access the private variable outside object. To change the name of the boy object we have to use the internal method:

<code>boy.setName('ravi') // will change the name variable
boy.getName() // will return ravi
</code>

Here we simply declared the variable as var =name, and this type of declaration made this variable unaccessible outside the object.

There is another type of coding pattern to make an object known as ‘object literals’:

<code>var MyObject={
  name : 'p',
  getName : function(){
    return this.name;   
  }
}
</code>

This coding pattern has two problems:

  1. An object in this state cannot be used as a constructor function.
  2. This object literal cannot support private variables.

This code cannot be used to instantiate many objects (to make many boy objects). But there is a function available in Javascript to instantiate this piece of code: Object.create(). To instantiate the object, we just pass the prototype in this function to get an object: var boy=Object.create(MyObject)

If Object.create() is not supported in a browser then we can use this fallback function:

<code>if(typeof Object.create != 'function'){
  Object.create=function(proto){
    var OBJ= function(){};
    OBJ.prototype=proto;
    return new OBJ();
  }
}
</code>

Now we can use this method even if our browser natively not supporting the Object.create() function.

Constructors

In Javascript, an object constructor is merely a regular Javascript function. There is no special method needed to declare a constructor; all you have to do is to write function and instantiate this function using the new keyword.

Here is a short sample of a constructor in Javascript; we are going to use car for our object constructor:

<code>var car=function(args){
  var name=args;
  this.getName=function(){
    return name;
  }
  this.setName=function(args){
    name=args
  }
}  
</code>

In the above function we use car as a constructor of all car object we are going to create. We can use the new keyword to instantiate a car function to make new objects.

<code>var car1=new car("bmw");
var car2=new car("gm");
</code>

We have now created two instances of the object car: car1 and car2. We can now use each object independently as follows:

<code>car1.getName() // will return bmw
car2.setName("honda"); // will change the name of object 2 
car2.getName(); //will return honda
</code>

That’s all you need to know to get started with constructors in Javascript.

Prototypes

Prototyping is very powerful tool which can make super great code or super bad code.

Sometime we make a new object, other times we use build-in object like String, Array etc. Prototyping provides the facility to add, replace, or delete methods and variables in root objects so all instance of an object can use a function regardless of when the function is declared.

Our previous object MyObject was instantiated using three variables:

<code>var suresh=new MyObject('suresh');
var ramesh=new MyObject('ramesh');
var sheeta=new MyObject('sheeta');
</code>

After creating all the objects, we realized there is another variable required for all the objects: gender.

Instead of adding the variable in for all the objects or using our previous function (which can sometimes be a headache), we can add one property in the constructor by which all objects were instantiated (MyObject): MyObject.prototype.gender='None'; or suresh.constructor.prototype.gender='None';.

We can add the property into the MyObject prototype, which all objects who inherit from MyObject automatically get.

In the above (admittedly simple) prototype, this functionality may not look very useful but take my word it, you’ll love this in the future. Lets suppose we want to reverse a string to create some kind of encryption or something else and we want to do it often, its best to call it as a property rather than explicitly calling a function; we can do this using prototype of constructor.

<code>String.prototype.reverse=function(){
    text=this.split('');
    rvr=text.reverse();
    rvr=rvr.join('');
    return rvr;
}
</code>

Above we used a Javascript built-in object called String. We used a prototype property of the String object to add our custom function to it. By doing this, all String objects automatically inherit the custom functionality.

Now we can use this custom function to reverse any string we want: var x="Pradeep".reverse();. This will return peedarP. Alternatively, we could writevar x="Pradeep"; x=x.reverse(); which will also return peedarP.

Now that you’ve gotten a taste of prototyping, use your imagination :P!

Subscribe to our blog