Aaron Aaron - 1 year ago 72
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() {
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
is there and
instead of assigning the object to
it is assigned to
. 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.

Answer Source
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download