Code gotten from MDN:
function Employee() {
this.name = "";
this.dept = "general";
}
function Manager() {
Employee.call(this);
this.reports = [];
}
Manager.prototype = Object.create( Employee.prototype );
function WorkerBee() {
Employee.call(this);
this.projects = [];
}
WorkerBee.prototype = Object.create( Employee.prototype );
var x = new WorkerBee();
console.log( x );
Output: WorkerBee {name: "", dept: "general", projects: Array[0]}
What effect does Employee.call(this); have? I know from running the code that it is necessary for inheritance to be successful. The docs for .call() simply state,
method calls a function with a given this value and arguments provided individually.
OK so it calls the constructor Employee() but there is no new operator being used and no return that would return the object and it's properties. How does Employee.call(this) cause the child object to inherit the parent properties?
If this line is left out only the projects array is present as a property.
What call does is simply invokes function with given context this. In your example it means that function Employee is called with this inside of it being instance of WorkerBee. So what happens in this case is that when Employee is executed it creates and sets own properties to the this object which at this moment WorkerBee.
Check what console logs when you run the code:
function Employee() {
console.log(this instanceof WorkerBee);
this.name = "";
this.dept = "general";
}
... and you will see that this is indeed points to the object instance of WorkerBee.
This pattern is used to make one constructor create own properties on the external host object (context). It's also called "borrowing constructor".
Employee.call(this); runs the function Employee with this within the function bound to the parameter. Somewhat confusingly, the parameter is this. When Employee.call(this); is run, this is a reference to the WorkerBee object that is being created with new.
With Employee.call(this);, the Employee function adds additional properties to the WorkerBee object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With