JavaScript Inheritance Using .call (this)

Code obtained 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 ); 

Exit: WorkerBee {name: "", dept: "general", projects: Array[0]}

What effect does Employee.call(this); ? I know that starting code that is necessary for inheritance will succeed. The docs for .call() just indicate

the method calls the function with the given value and the arguments separately.

OK, so it calls the Employee() constructor, but it does not use the new operator, not return , which returns the object and its properties. How does Employee.call(this) force a child to inherit its parent properties?

If this line is not specified, only the projects array is present as a property.

+6
source share
3 answers

What call does is simply calling the function with the given this context. In your example, this means that the Employee function is called with this inside it, which is an instance of WorkerBee . So in this case, what happens is that when Employee executes, it creates and sets its own properties for the this object, which is currently a WorkerBee .

Check which console logs are executed when the code runs:

 function Employee() { console.log(this instanceof WorkerBee); this.name = ""; this.dept = "general"; } 

... and you will see that this really points to an instance of the WorkerBee object.

This template is used so that one constructor creates its own properties of the external object (context) of the host. It is also called a "borrower."

+2
source

Employee.call(this); runs the Employee function with this inside the function associated with the parameter. Somewhat vaguely, this parameter. When Employee.call(this); started, this is a reference to the WorkerBee object that is created with new .

With Employee.call(this); The Employee function adds additional properties to the WorkerBee object.

+2
source

Employee is just a function, like any other function. When used with the new operator, it acts on a newly allocated object of type Employee ", but this is not the only way to call it.

In the script that you mean, it just populates the name and dept this properties.

0
source

Source: https://habr.com/ru/post/989646/


All Articles