Aaron Aaron - 3 months ago 7
Javascript Question

Javascript Inheritance call behaviour

Was going through Mozilla's Reference and came across this simple relationship.

function Employee() {
this.name = "";
this.dept = "general";
}

function Manager() {
Employee.call(this);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);


Apparantly, this forms a inheritance-like relationship from the Employee to the Manager.

Two questions here, Not sure what and why
Employee.call(this);
is there and
instead of assigning the object to
Employee.prototype
it is assigned to
Manager.prototype
. My thoughts were that Manager is inheriting from Employee, not vice versa. Perhaps this is the concept of the prototype chain where it really means both objects can grab properties from each other?

Would like some clarification.

J F J F
Answer
  1. Employee.call(this) is like calling Employee(), but instead of using it to create a new object, it instead modifies the current Manager. In this example, it sets name and dept in the Manager.
  2. This statement:

    Manager.prototype = Object.create(Employee.prototype);
    

    means that any attributes set like Employee.prototype.x = val will also be available in Manager.prototype; however if you override them in Manager.prototype, they will be overriden.
    You should also run Manager.prototype.constructor = Manager to make that property correct.

Comments