JavaScript Inheritance

May 11, 2015 in Web Development Articles

Written by Todd Wright


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

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.


Written by Todd Wright

Todd Wright

Todd is a Java developer and trainer specializing in Enterprise Java Technology (J2EE), Perl, and XML related software. Todd is a published author of several software development and design technical training books.


Learn faster

Our live, instructor-led lectures are far more effective than pre-recorded classes

Satisfaction guarantee

If your team is not 100% satisfied with your training, we do what's necessary to make it right

Learn online from anywhere

Whether you are at home or in the office, we make learning interactive and engaging

Multiple Payment Options

We accept check, ACH/EFT, major credit cards, and most purchase orders



Recent Training Locations

Alabama

Birmingham

Huntsville

Montgomery

Alaska

Anchorage

Arizona

Phoenix

Tucson

Arkansas

Fayetteville

Little Rock

California

Los Angeles

Oakland

Orange County

Sacramento

San Diego

San Francisco

San Jose

Colorado

Boulder

Colorado Springs

Denver

Connecticut

Hartford

DC

Washington

Florida

Fort Lauderdale

Jacksonville

Miami

Orlando

Tampa

Georgia

Atlanta

Augusta

Savannah

Hawaii

Honolulu

Idaho

Boise

Illinois

Chicago

Indiana

Indianapolis

Iowa

Cedar Rapids

Des Moines

Kansas

Wichita

Kentucky

Lexington

Louisville

Louisiana

New Orleans

Maine

Portland

Maryland

Annapolis

Baltimore

Frederick

Hagerstown

Massachusetts

Boston

Cambridge

Springfield

Michigan

Ann Arbor

Detroit

Grand Rapids

Minnesota

Minneapolis

Saint Paul

Mississippi

Jackson

Missouri

Kansas City

St. Louis

Nebraska

Lincoln

Omaha

Nevada

Las Vegas

Reno

New Jersey

Princeton

New Mexico

Albuquerque

New York

Albany

Buffalo

New York City

White Plains

North Carolina

Charlotte

Durham

Raleigh

Ohio

Akron

Canton

Cincinnati

Cleveland

Columbus

Dayton

Oklahoma

Oklahoma City

Tulsa

Oregon

Portland

Pennsylvania

Philadelphia

Pittsburgh

Rhode Island

Providence

South Carolina

Charleston

Columbia

Greenville

Tennessee

Knoxville

Memphis

Nashville

Texas

Austin

Dallas

El Paso

Houston

San Antonio

Utah

Salt Lake City

Virginia

Alexandria

Arlington

Norfolk

Richmond

Washington

Seattle

Tacoma

West Virginia

Charleston

Wisconsin

Madison

Milwaukee

Alberta

Calgary

Edmonton

British Columbia

Vancouver

Manitoba

Winnipeg

Nova Scotia

Halifax

Ontario

Ottawa

Toronto

Quebec

Montreal

Puerto Rico

San Juan