I'm having some trouble deciphering prototypical inheritance in JavaScript, and thought of posting it here. Consider this simple example:
function Employee() {
this.name = "Rob";
this.dept = "R&D";
}
function Manager() {
//Employee.call(this);
this.reports = ["Report 1", "Report 2", "Report 3"];
}
Manager.prototype = Object.create(Employee.prototype);
Employee.prototype.type = "human";
m = new Manager();
console.log(m.name); //undefined
console.log(m.type); //human
What I can't understand is the utility of the line Employee.call(this)
. Since we're going to be setting Employee.protoype as Manager's prototype, what's the need for (as I see it) explicitly forcing the creation of variables in Employee through call()
? Earlier I thought that it might be because no object of Employee
exists, and JS inheritance can't work without objects, so call()
here served to "complete the object build". But then, the type
property gets reflected in Manager without the need for call()
, which proves that we don't need a hard object to perform inheritance (what I mean is, just the class-like constructor function definition will do).
I hope I haven't made it too complicated. In short: Why is call()
needed here, and why does the property type
work without call()
(if call()
is that important, that is).
The purpose of Employee.call(this)
is to add name and department attributes to Manager instances.
Usage of call()
is more by convention and it allows to modify the caller (this) in place.
The property type
worked since you went through the prototype interface.
If you uncomment the Employee.call(this)
, then m.name will become 'Rob'.
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