Your privacy matters: This site uses cookies to analyze site usage and provide social media features. Learn More.

Inheritance in JavaScript

May 11, 2015 in JavaScript Articles

Written by Todd Wright


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.


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.


Contact Us:

Accelebrate’s training classes are available for private groups of 3 or more people at your site or online anywhere worldwide.

Don't settle for a "one size fits all" public class! Have Accelebrate deliver exactly the training you want, privately at your site or online, for less than the cost of a public class.

For pricing and to learn more, please contact us.

Contact Us

Toll-free in US/Canada:
877 849 1850
International:
+1 678 648 3113

Toll-free in US/Canada:
866 566 1228
International:
+1 404 420 2491

925B Peachtree Street, NE
PMB 378
Atlanta, GA 30309-3918
USA

Subscribe to our Newsletter:

Never miss the latest news and information from Accelebrate:

Microsoft Partner

Please see our complete list of
Microsoft Official Courses

Recent Training Locations

Alabama

Huntsville

Montgomery

Birmingham

Alaska

Anchorage

Arizona

Phoenix

Tucson

Arkansas

Fayetteville

Little Rock

California

San Francisco

Oakland

San Jose

Orange County

Los Angeles

Sacramento

San Diego

Colorado

Denver

Boulder

Colorado Springs

Connecticut

Hartford

DC

Washington

Florida

Fort Lauderdale

Miami

Jacksonville

Orlando

Saint Petersburg

Tampa

Georgia

Atlanta

Augusta

Savannah

Idaho

Boise

Illinois

Chicago

Indiana

Indianapolis

Iowa

Ceder Rapids

Des Moines

Kansas

Wichita

Kentucky

Lexington

Louisville

Louisiana

Banton Rouge

New Orleans

Maine

Portland

Maryland

Annapolis

Baltimore

Hagerstown

Frederick

Massachusetts

Springfield

Boston

Cambridge

Michigan

Ann Arbor

Detroit

Grand Rapids

Minnesota

Saint Paul

Minneapolis

Mississippi

Jackson

Missouri

Kansas City

St. Louis

Nebraska

Lincoln

Omaha

Nevada

Reno

Las Vegas

New Jersey

Princeton

New Mexico

Albuquerque

New York

Buffalo

Albany

White Plains

New York City

North Carolina

Charlotte

Durham

Raleigh

Ohio

Canton

Akron

Cincinnati

Cleveland

Columbus

Dayton

Oklahoma

Tulsa

Oklahoma City

Oregon

Portland

Pennsylvania

Pittsburgh

Philadelphia

Rhode Island

Providence

South Carolina

Columbia

Charleston

Spartanburg

Greenville

Tennessee

Memphis

Nashville

Knoxville

Texas

Dallas

El Paso

Houston

San Antonio

Austin

Utah

Salt Lake City

Virginia

Richmond

Alexandria

Arlington

Washington

Tacoma

Seattle

West Virginia

Charleston

Wisconsin

Madison

Milwaukee

Alberta

Edmonton

Calgary

British Columbia

Vancouver

Nova Scotia

Halifax

Ontario

Ottawa

Toronto

Quebec

Montreal

Puerto Rico

San Juan

© 2013-2019 Accelebrate, Inc. All Rights Reserved. All trademarks are owned by their respective owners.