US & Canada: 877 849 1850
International: +1 678 648 3113

Accelebrate Blog

ACCELERATED LEARNING, CELEBRATED RESULTS

Inheritance in JavaScript

What I Wish I Had Picked up in Introduction to JavaScript. Pt 4

An earlier article dove into Prototypes. If you don’t recall what they are you should read my Prototypes in JavaScript post before continuing to read this article about inheritance in JavaScript.

Inheritance is an OO (object-oriented) concept that provides one of the most critical of all relationships in the class hierarchy: Parent-Child (SuperClass, SubClass). The parent class provides core concepts that are extended in the child class and is an abstraction of the child type. In many languages this relationship is clearly articulated, and clearly “protected”. This is not the case in JavaScript.

JavaScript is a language that can support OO, but it is not at its heart OO. With the advent of Java and the proliferation of OO design, the natural trend of implementing OO solutions in JavaScript was inevitable. There are several techniques to provide the Parent-Child relationship, but Prototypes is the most common form.

A Parent class is defined:

var Person = function(fn,ln,age){
    this.firstname=fn;
    this.lastname=ln;
    this.age=age;
  };

The method named “Person” is going to act like a class. The class will hold properties and methods, but any properties and methods that are defined here will be added to each instance of the class.

The prototype is commonly used to add methods to objects. Its singleton nature makes prototypes very efficient at holding common properties and methods.

Person.prototype.sayHello = function(){
  return "Hello, My name is "+this.firstname +" " + this.lastname;
}

The use of the keyword this inside a function will point to the context of the function call. For example, notice bob.sayHello() inside the sayHello Function. Here, “this”, would point to the bob object. The constructor is called with the JavaScript new keyword “new.” This will create an object, assign a reference to the constructor and prototype, and then invoke the Constructor function on the object (see the JavaScript apply() function). In the constructor, the keyword this will point to the newly created object.

var bob = new Person("Bob","Wallace",42);
var sue = new Person("Sue","Smoothers",35);

bob.sayHello();
sue.sayHello();

Not really anything overly complex. If our model needed to define a more specialized form of “Person”, then we should create an Employee class. The Employee class will add empid and jobtitle properties.

var Employee = function(fn,ln,age,eid,title){
  this.empid=eid;
  this.jobtitle=title;
  this.firstname=fn;
  this.lastname=ln;
  this.age=age;
};

The Employee type is a stand-alone class. It shares properties (and probably methods) with the Person class, but there is no relationship with the parent. Building this relationship with the parent can take several forms, but the most common is to use an instance of the parent as the prototype:

Employee.prototype = new Person();
Employee mike = new Employee("Mike","Collins",32,4,"Master of IT");

mike.sayHello();

JavaScript Inheritance Flow Chart

In this solution, the Employee constructor is responsible for assigning all the properties of the new Employee. An alternative would be Person.call(this,firstname,lastname,age), which would invoke the Person method using the current object as the context.

This solution to inheritance fulfills the majority of needs for inheritance, however it is a bit ugly. In the above solution, there is an extra call to the Person constructor to create the anonymous object that is used as the prototype for Employee. This could be a problem if the Person class had an instance counter or similar behavior. The inheritance solution in JavaScript is not perfect, but like most things in the language, it is clever and works well enough for most needs.

Many JavaScript libraries have picked up on the difficulties that are posed with the implementation of inheritance in JavaScript and they usually provide their own answer. For example jQuery uses the $.extend() method and ExtJS uses the extend property in the define method. If you are using these libraries, you will likely use these approaches instead of Prototype.

This said, in the absence of a framework managing the details of inheritance in your JavaScript code, proper use of prototypes can be an effective way to implement inheritance in your JavaScript code.


Author: Todd Wright, one of Accelebrate’s instructors Accelebrate offers private JavaScript training for groups and instructor-led online JavaScript classes for individuals.

Categories: JavaScript Articles
Tags: , , , , , , ,

3 Responses to "Inheritance in JavaScript"

Leave a Reply

Your email address will not be published. Required fields are marked *

Your email address will not be published. Required fields are marked *

*



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please contact us for GSA pricing.
Contract #GS-35F-0307T

Please see our complete list of
Microsoft Official Courses