Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the need for call() in prototypical inheritance

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).

like image 431
ankush981 Avatar asked Jul 03 '15 11:07

ankush981


1 Answers

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'.

like image 189
Christian MICHON Avatar answered Oct 20 '22 14:10

Christian MICHON