0

Please find my two methods of creating inheritance. Can some one explain me what going on with each type.

Method 1:

function Person(name){
    this.name = name;
}

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

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

Employee.prototype = new Person();
Employee.prototype.constructor = Employee;

Employee.prototype.getDesignation = function(){
    return this.designation;
}

new Employee("Jagadish", "Cons");

enter image description here

Method 2:

function Person(name){
    this.name = name;
}

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

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

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

Employee.prototype.getDesignation = function(){
    return this.designation;
}

new Employee("Jagadish", "Cons");

enter image description here

I have inserted the images of console of each object. In first method i can see name property in Person class which is undefined (refer first screenshot).

But in case of second method of inheritance i dont have name property in Person class.

Can someone explain in depth about this behavior and what is happening in background.

1 Answers1

1

There is nothing magical going on here, the program is doing exactly what it is told to do.

When you are calling new Person, you are creating a new object. That object has a name property because you are explicitly assigning to this.name inside the function.

Object.create however creates an empty object, unless it is passed a second argument with property descriptors.


To explain the specific difference between Object.create and new A:

new A():

  • Create a new object inheriting from A.prototype
  • Apply A to the new object, i.e. call A.call(newObj)

Object.create(A.prototype):

  • Create a new object inheriting from A.prototype

So you see, the specific difference between those two calls is that with new the function is applied to the new object, with Object.create is isn't.


Related: Benefits of using `Object.create` for inheritance

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks for your answer but i am still confused. I want to know how this statement Person.call(this, name); is creating name property in Employee class – Jagadish Dharanikota Mar 26 '15 at 06:17
  • Are you just not familiar with what `call` does? It executes the function and sets its `this` value to the first passed argument. If you had `var obj = {}; Person.call(obj, 'foo');`, then the `name` property is set on `obj`. – Felix Kling Mar 26 '15 at 06:31