Friday, December 4, 2015

JavaScript Constructor Prototype

At first it's important to understand that in JavaScript every function is an Object. Ok - then, what is a Constructor function?

The Construction function in javascript is just like any other function. Except, the convention it follows - Capitalization. The first character is in capital format. Another difference is that it uses the 'this' keword of javascript, which is the most important and confusing keyword of all.

This is how we create the constructor function:
function Student(name){
  this.name = name;
  this.getName = function(){
    return this.name;    
  }
}
var s1 = new Student("Leo");
var s2 = new Student("Lara");

console.log(s1.getName()); //Leo
console.log(s2.getName()); //Lara
This is not an appropriate way because if you create 500 Student objects then there will be 500 copies of the getName() function in memory.

Approach 2:
function Student(name){
  this.name = name;
}
var s1 = new Student("Leo");
s1.getName = function(){
  return this.name;
}
var s2 = new Student("Lara");

console.log(s1.getName()); //Leo
console.log(s2.getName()); //TypeError: s2.getName is not a function
The problem with this approach is that you have to repeat the same function for each object you create which will be arror prone.

Approach 3:
function Student(name){
  this.name = name;
}
Student.getName = function(){
  return this.name;
}
var s1 = new Student("Leo");
var s2 = new Student("Lara");

console.log(s1.getName()); //TypeError: s1.getName is not a function
console.log(s2.getName()); // 
The problem with this approach is that our newly created objects don't have access to the getName function.

Let's use the prototype property to associate the function
function Student(name){
  this.name = name;
}
Student.prototype.getName = function(){
  return this.name;
}
var s1 = new Student("Leo");
var s2 = new Student("Lara");

console.log(s1.getName()); //Leo
console.log(s2.getName()); //Lara

1. The benefits of this approach is that no matter how many objects you create, functions are loaded only once in the memory.
2. It allows you to override the function if necessary



No comments:

Post a Comment