Search code examples
javascriptprototypal-inheritancefunction-constructor

How to visualize representation of Function constructor objects?


For below code,

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

below is my understanding on visualizing the representation of above code,

enter image description here

For below code,

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

below is my understanding on visualizing the representation of above code,

enter image description here

Are the above diagrams an accurate representation of the prototype chain created by this Javascript code?

Note: Javascript beginner


Solution

  • The first one is fine on the first look (except maybe for ugly graphics, but that wasn't the question). If you care for UML, you should not put __proto__1 and prototype next to each other but rather one above the other.

    Also, it's important to notice that the Employee constructor function does not have .name2 and .dept properties. A new Employee instance would have these.

    In the second there are a couple more mistakes:

    • Again, the Manager function does not have a reports property. A new Manager instance would have name, dept and reports properties.
    • The right prototype object is Manager.prototype, not Employee.prototype (of which you have two). That's just a labeling issue of course, but still important for precise referencing the graphics.
    • The Manager.prototype's __proto__ is not Object.prototype, but rather Employee.prototype - that's what you've used Object.create for.
    • The Object.create(…) should not label the arrow, but rather the object itself (of course that's more a style issue, you don't use a spec, do you?)
    • The Manager.prototype does not have a constructor property. It does inherit the one from Employee.prototype though. You should consider creating one in your code though, see Why is it necessary to set the prototype constructor?. It would then point to Manager.

    1: Actually, __proto__ is a getter/setter property on the Object.prototype object. The real, internal prototype link (that is only accessible via Object.set/getPrototypeOf) is typically designated as [[prototype]].
    2: In fact, the Employee function does have a .name property, but not the one you meant.