0

The below code is using inheritance using Prototype, its as follows ,

function Employee(name){
  var name = name;

  this.getName = function(){
    return name;
  }

  this.toString = function(){
    var str = "";
    str +=  "Name : "+this.getName()+
            "\nStreet : "+this.getStreet()+
            "\nPostal Code : "+this.getPostalCode();
    return str;
  }
}

function Address(street,postalCode){
 var street = street,
    postalCode = postalCode;

 this.getStreet = function(){               
    return street;
 };

 this.setStreet = function(str){
    street = str;               
 };

 this.getPostalCode = function(){
    return postalCode;  
 };

 this.setPostalCode = function(pc){
    postalCode = pc;
 };      
}

Employee.prototype = new Address(); // Prototype chaining

var emp1 = new Employee("Ram Patel");

emp1.setStreet("Katiar Road, Ahamadabad, Gujurat");
emp1.setPostalCode("3455454");

console.log(emp1.toString());

When the above code runs the output is

Name : Ram Patel
Street : Katiar Road, Ahamadabad, Gujurat
Postal Code : 3455454

Now Inheritance using method call, please follow the code bellow,

function Employee(name){
var name = name;

Address.call(this);

this.getName = function(){
    return name;
}

 this.toString = function(){
    var str = "";
    str +=  "Name : "+this.getName()+
            "\nStreet : "+this.getStreet()+
            "\nPostal Code : "+this.getPostalCode();
    return str;
 }
}

function Address(street,postalCode){
  var street = street,
      postalCode = postalCode;

  this.getStreet = function(){              
    return street;
  };

  this.setStreet = function(str){
    street = str;               
  };

  this.getPostalCode = function(){
    return postalCode;  
  };

  this.setPostalCode = function(pc){
    postalCode = pc;
  };         
}



var emp1 = new Employee("Peter Thiel");

emp1.setStreet("32 St. John Street, Washinton");
emp1.setPostalCode("3455242");

console.log(emp1.toString());

The output when I run the above code is

Name : Peter Thiel
Street : 32 St. John Street, Washinton
Postal Code : 3455242

So from above we can see that inheritance in both the ways works fine in JavaScript.

So that makes the difference if I use

Employee.prototype = new Address();

Above this,

function Employee(name){
  var name = name;

  Address.call(this);
Rahul Shivsharan
  • 2,481
  • 7
  • 40
  • 59
  • An employee is not an address! Use [composition over inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance)! – Bergi Nov 02 '16 at 11:49
  • In your first attempt, try to create two instances and print them both. Then see it fail. – Bergi Nov 02 '16 at 11:52

0 Answers0