Lets create an Employee constructor function with the following instance properties.
const Employees = function (empName, empId, dept, doj) {
this.empId = empId;
this.empName = empName;
this.dept = dept;
this.doj = doj;
};
Lets create a method on the Employee prototype.
Employees.prototype.empDetails = function () {
console.log(
`${this.empName} with employee id ${this.empId} had joined the ${this.dept} department on ${this.doj}`
);
};
Now lets create another constructor function ,Manager which inherits from Employee constructor. Can we just invoke the Employee constructor as shown below. The answer is NOβπ.Why though ? The following code is a regular function call and in a regular function call the this keyword is undefined.
const Manager = function (empName, empId, dept, doj) {
Employees(empName, empId, dept, doj);
};
Instead we use the call() with the this keyword.
Now what does the this keyword point to? It is the newly created Manager object. We ask the Employees constructor to update the values of Manager object while we pass a reference of the object to the Employees constructor.
const Manager = function (empName, empId, dept, doj) {
Employees.call(this, empName, empId, dept, doj);
};
Now lets create prototype object for Manager.
But how ? The following is NOTβπ to be done as both the prototypes point to the same object.
//Manager.prototype = Employees.prototype;
Instead we create a new object with Employee prototype properties.
Manager.prototype = Object.create(Employees.prototype);
Creating an instance.
const george = new Manager('George', 200, 'finance', '24th August 2000');
george.manage();
//inheriting parent constructor methods
george.empDetails();
Until the next one Break,Code,Repeat!π