Let us look at the following code snippet:
//constructor function
const Employee = function (empId, empName) {
//instance properties
this.empId = empId;
this.empName = empName;
};
This is a basic constructor , now what if I want to add a method to the above code ?Do I add the method as a property to the constructor function ? The answer is NO.
The reason is simple - every time the constructor is invoked a new object is created for the method , essentially creating 100 objects for a 100 constructor call. We rather add the method to a prototype property of the constructor function.
Employee.prototype.addDept = function (deptName) {
this.deptName = deptName;
};
const maria = new Employee(101, 'Maria');
maria.addDept('Accounting');
What happens internally ?
Let us look at the following image to understand with reference to our code.
Basically the Employee has a prototype property which points to the Employee.prototype object. The Employee.prototype object has a reference back to the Employee.
Phew! Now what happens when an instance of Employee is created ? Let's visualize!
const maria = new Employee(101, 'Maria');
The following happens :
1. An empty object is created.
2.This keyword of the constructor function points to the newly created object in the JS execution context.
3.The newly created object points to the constructor function's prototype property. Really how ? When an object is created JS engine automatically creates a _ _proto_ _ property which points to the constructor function's prototype.
4.The newly created object is returned from the Employee constructor function call . (eg : maria)
Now what happens in this line of code ?
maria.addDept('Accounting');
JS searches for this method in the instance object. It wouldn't be able to find.When a property cannot be found in the object , it is searched in the prototype.
This is known as Prototypal inheritance.The object maria inherits the addDept() from its prototype.
Until the next one , let us Break,Code,Repeat ! ๐