JavaScript Inheritance

JavaScript supports inheritance, which allows us, when creating new types of objects, if necessary, to inherit their functionality from existing ones. For example, we might have a User object representing an individual user. And there can also be an Employee object that represents an employee. But a worker can also be a user and therefore must have all of its properties and methods. For example:

// user constructor
function User (name, age) {
    this.name = name;
    this.age = age;
    this.go = function(){document.write(this.name + " goes <br/>");}
    this.displayInfo = function(){
        document.write("Name: " + this.name + "; age: " + this.age + "<br/>");
    };
}
User.prototype.maxage = 110;

// worker constructor
function Employee(name, age, comp){
    User.call(this, name, age);
    this.company = comp;
    this.displayInfo = function(){
        document.write("Name: " + this.name + "; age: " + this.age + "; company: " + this.company + "<br/>");
    };
}
Employee.prototype = Object.create(User.prototype);

var tom = new User("Tom", 26);
var bill = new Employee("Bill", 32, "Google");
tom.go();
bill.go();
tom.displayInfo();
bill.displayInfo();
console.log(bill.maxage);
[js]

Here, it first defines the User constructor and adds a property to its prototype maxage. Then the Employee type is defined.

In the Employee constructor, the User constructor is accessed by calling:

[js]
User.call(this, name, age);

Passing the first parameter allows you to call the User constructor function on the object that the Employee constructor creates. This ensures that all properties and methods defined in the User constructor are also passed onto the Employee object.

In addition, the User prototype must also be inherited. To do this, the call is:

Employee.prototype = Object.create(User.prototype);

The method Object.create() allows you to create a User prototype object, which is then assigned to the Employee prototype. At the same time, if necessary, we can also define additional properties and methods in the Employee prototype.

When inheriting, we can redefine the inherited functionality. For example, Employee overrides a method displayInfo()that is inherited from User to include a new property in that method’s output company.

As a result, the browser will provide the following output: