JavaScript (Prototypal) Inheritance with new and Object.create


//---------------------------
//Inheritance in JavaScript
//---------------------------

var Person = function (string){
 this.name= string;
 
  //if ( !(this instanceof Person) ) //part soln to danger 1
    //  return new Person(name);
};

Person.prototype.get_name = function(){
 return this.name;
};


//Danger 1 : No compile errors here if new is skipped
//Also inside the function would now be the global this object,
//not the new instance! The constructor would be overriding all sorts
//of global variables inadvertently
var manu = Person("Manu");
name;
manu.get_name(); //Danger 1 :only run time error here;Crackford's reason

var adi =  new Person("Adi");
adi.get_name();

//Okay let us try Iheritance with new 

var Employee = function (name,company){
  this.name = name;
  this.company=company;
  Person.call(this,name);
  
};

Employee.prototype.get_company = function(){

 return this.comany;
};

//How to inherit from Person ?
//Step 1 - Link the prototypes //very similar to Object.create see below
Employee.prototype = new Person();

var naresh =  new Employee("Naresh","NSN");
naresh;
naresh.get_name();
naresh.get_company(); // oops, inheritance not complete

//Need to set the prototype after step 1
//Step 2
Employee.prototype.get_company = function(){

 return this.company;
};


var palani =  new Employee("Palani","NSN");
palani;
//perfect
palani.get_company();
palani.get_name();

//---------------Another way with Obect.create--------------------------

function Manager(name,company){

  Employee.call(this,name,company);
};

Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor = Manager; //correct the ctor
Manager.prototype.getTeamSize = function(){
   return 5;
}

var guru = new Manager("Guru","NSN");

guru.get_name();
 guru.get_company() ;
 guru.getTeamSize();

Comments

Popular posts from this blog

Long running Java process resource consumption monitoring , leak detection and GC tuning

Best practises - Selenium WebDriver/ Java

Java Script Development Guidlines