[JavaScript] Inheritance

You can reuse the code through Inheritance in JavaScript too. The key point is to use the “prototype” object. By setting the parent object to the “prototype“, you can inherit members from the parent class.

 

1. Creating a Child Class

There are a couple of steps to do to create a sub class.

  • ChildClassName.prototype = new ParentClass(); // inherit class
  • ChildClassName.prototype.constructor = ChildClassName // replace the constructor
  • In the constructor function of a child class, call the parent class’s constructor using the “call()” method

In ES2015 class syntax make you define a sub class easier.

 

2. Example – Parent Class

Let’s create the parent class.

function Employee() {
  this.id = 0;
}
Employee.prototype.isFullTime = function () { return true; };
Employee.prototype.getStatus = function () {
  alert("Employee " + this.id + " is a " + (this.isFullTime() ? "full time" : "part time") + " employee.");
};

 

3. Example – Child Class

Now create the child class.

function PartTimeEmployee() {
  Employee.call(this);
}
PartTimeEmployee.prototype = new Employee();
PartTimeEmployee.prototype.constructor = PartTimeEmployee;

 

4. Overriding Methods

You can freely override the method in the child class.

PartTimeEmployee.prototype.isFullTime = function () { return false; }; // overridden

 

5. Example – Full Code

Here is the full code example.

function Employee() {
  this.id = 0;
}
Employee.prototype.isFullTime = function () { return true; };
Employee.prototype.getStatus = function () {
  alert("Employee " + this.id + " is a " + (this.isFullTime() ? "full time" : "part time") + " employee.");
};

function PartTimeEmployee() {
  Employee.call(this);
}
PartTimeEmployee.prototype = new Employee();
PartTimeEmployee.prototype.constructor = PartTimeEmployee;

PartTimeEmployee.prototype.isFullTime = function () { return false; }; // overridden

$("document").ready(function () {
  var emp1 = new Employee();
  emp1.id = 1;

  var emp2 = new PartTimeEmployee();
  emp2.id = 2;

  emp1.getStatus();
  emp2.getStatus();
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s