"Global information in designers" in the MDN JavaScript manual, small request

In the JavaScript MDN guide in the section “Inheritance of properties is inherited”, he explains some of the subtleties of property inheritance.

In particular, I am interested, for example, with an incremental id example:

var idCounter = 1;

function Employee (name, dept) {
this.name = name || "";
this.dept = dept || "general";
this.id = idCounter++;
}

function Manager (name, dept, reports) {...}
Manager.prototype = new Employee;

function WorkerBee (name, dept, projs) {...}
WorkerBee.prototype = new Employee;

function Engineer (name, projs, mach) {...}
Engineer.prototype = new WorkerBee;

function SalesPerson (name, projs, quota) {...}
SalesPerson.prototype = new WorkerBee;

var mac = new Engineer("Wood, Mac");

Basically, it goes on to say that a complete version of this (each constructor has a “base” property, which also calls the constructor above them in the prototype chain) will mean that mac.id will be 5.

I understand that every time an Employee object is created, the id value is incremented by 1, but exactly, when 4 times before creating a "mac" an Employee object is created? I would be grateful if someone could give me a step-by-step process.

edit - , : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Global_information_in_constructors

+4
2

new . , ( new, , (), call apply), . :

Manager.prototype = new Employee; //1
//...
WorkerBee.prototype = new Employee; //2

. :

, base .

, {...} :

function Manager (name, dept, reports) {
    Employee.apply(this, arguments);
}

jsFiddle ( ).

, Employee:

Engineer.prototype = new WorkerBee; //3
//...
SalesPerson.prototype = new WorkerBee; //4
//...
var mac = new Engineer("Wood, Mac"); //5
+3

, . .

:

Manager Employee, Manager.prototype Employee. , Manager.prototype = new Employee Employee.

, , - , init:

function Employee() { /* EMPTY CONSTRUCTOR */ }
Employee.prototype.init = function(name, dept) {
  this.name = name || "";
  this.dept = dept || "general";
  this.id = idCounter++;
}

function Manager(name, dept, reports) {
    this.init(name, dept); // Calls the base constructor
}
Manager.prototype = new Employee();
0

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


All Articles