...

/

Inheritance in Constructor Functions

Inheritance in Constructor Functions

Introduction to inheritance in the constructor functions in JavaScript.

In this lesson, we will implement inheritance on the constructor functions.

Prototypes in the constructor functions

We know that inheritance in JavaScript can be implemented through prototypal inheritance. This is when we manage to manipulate __proto__ properties of an object so it can inherit properties from other objects. Before we can move onto inheritance between constructor functions, let’s revisit the prototype property of objects created using constructor functions through the lens of inheritance.

Revisit the following example.

Press + to interact
function Employee(_name, _age, _designation){
// Properties assignment passed as arguments
this.name = _name;
this.age = _age;
this.designation = _designation;
// Method
this.setAge = newage => {
console.log(`setting age from ${this.age} to ${newage}`)
this.age = newage;
}
// Property assigned by constructor function
this.company = 'Amazon';
}
var employee1 = new Employee('Mark', 20, 'Manager'); // create Employee object
var employee2 = new Employee('Bob', 30, 'Accountant'); // create Employee object
// Print Employee objects prototype objects
console.log(`employee protoypes: ${employee1.__proto__}, ${employee2.__proto__}`);
console.log(`protoype equalities: ${employee1.__proto__ === employee2.__proto__}`);
console.log(`protoype equalities: ${Employee.prototype === employee2.__proto__}`);
console.log(Employee, Employee.__proto__, Employee.prototype);

We know that all objects created through Employee constructor function share the same prototype property __proto__, is equivalent to Employee.prototype. All objects inherit properties from their constructor functions. The figure below outlines the phenomena.

Here, all objects share the same link to the prototypal chain. They all inherit the same properties. If we modify the prototype object, then all objects’ ...