Monday, November 10, 2014

What is Prototype in javascript

I always had this issue on understanding what is prototype in javascript and finally, I had a much clearer picture thanks to a youtube video by Javavideotutorails (https://www.youtube.com/watch?v=JEJjbi5iqjc&list=PLOxOmO43E6Jt4GfZtF8yR6KghIdmc7715&index=4). 

You need to understand quite a few core topics about javascript before you can truly understand the beauty of prototype. Things like JSON, function declaration / expression declaration and etc. But to me, the light of enlightenment hit’s me when javascript constructor is mention.

Given this scenario: Create 2 persons with basic details and a function to print the first and last name.

First, we will write a person constructor that takes in firstName and lastName as the parameters

function Person (firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.getPersonName = function () {
    return this.firstName + “ “ + this.lastName;
  };
}


Declare some variables to hold the 2 persons

var p1 = new Person(“Angeline”,”Doe”);
var p2 = new Person(“Sarah”,”Doe”);

Each person object will contain first name and last name parameters, and also a function getPersonName tagged to it. 

In javascript, function is treated like an object that require memory to store it. For our case, both p1 and p2 will contain an additional function object (getPersonName) which practically do the same thing. Even tho they serve the same purpose, each getPersonName is a different instance that use up different memory.

This is where prototype comes into the picture. 

Take a look at this modified Person constructor.

function Person (firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

Person.prototype.getPersonName = function () {
  return this.firstName + “ “ + this.lastName;
};


All objects in javascript contains prototype object, and prototype object is a static object which is accessable by all similar type of object.

Here in this case, we are taking getPersonName function out and declare it under Person.prototype. By doing so, when we create p1 and p2, the Person object only contains firstName and lastName, and getPersonName became a static function object that both share. Hence, whenever you access getPersonName, it will always point to the same memory sector, which reduce the redundancy on having multiple getPersonName.


Hope this clarifies some of your doubts, and do talk to me if you have any questions regarding this.