Prototype Objects in JavaScript

January 13, 2015 in JavaScript Articles

Written by Todd Wright


What I wish I had picked up in Introduction to JavaScript. Pt 3

My early experiences with JavaScript began with version 1.0. It was a fantastic and wild time. Tons of mouseOver and scrolling banners. The world was great. Developers were learning, sharing, and inventing clever hacks to do amazing things in the browser. At the same time I was nose deep in this other fledgling language named Java. Java and JavaScript: two languages sharing a common base name, but with vast differences in their implementations of inheritance. Java supports object inheritance. Java uses the extends keyword to refine the definition of a type into a subtype. I got it. At the time my hope was for a similar concept in JavaScript. I was wrong. Instead of Java-style inheritance, I was left with fuzzy words like prototype and methods like .apply(). I was unhappy. JavaScript can provide inheritance and class hierarchy like Java, but it is done differently. First steps first: Prototype. Most implementations of inheritance in JavaScript are based on prototypes. Technically, prototypes are not “doing” inheritance, they are a tool to make us feel like there is inheritance – a discussion on prototypes is not necessarily a discussion about inheritance. So we will figure out prototypes first, and then let the application of this concept lead to inheritance later. JavaScript objects are critical. Objects contain properties and methods.

<script language="JavaScript">
  var driverslicense1 = {firstname :"Delois", lastname:"Price",
        show:function(){
           console.log("Licensee: "+this.firstname + " " + this.lastname)}
   };
   driverslicense1.show();
</script>

The single object instantiated above has three properties, one being a function. Creating a second object with a very similar structure makes OO developers everywhere cringe:

<script language="JavaScript">
  var driverslicense1 = {firstname :"Delois", lastname:"Price",
        show:function(){
           console.log("Licensee: " + this.firstname + " " + this.lastname)}
   };
   driverslicense1.show();   
  var driverslicense2 = {firstname :"Michael", lastname:"Bolton",
        show:function(){
           console.log("Licensee: " + this.firstname + " " + this.lastname)}
   };
   driverslicense2.show();
</script>

The function is repeated because the base JavaScript does not include our version of show(). This is one place where prototypes can be helpful. Every object in JavaScript is automatically and implicitly assigned a prototype object. JavaScript objects have an implicit variable named __proto__ .

Prototype Object

[click for larger image]

The prototype object becomes an entry in the “search path” for properties. If a property is trying to be resolved on an object and it is not found, JavaScript will look at that object’s prototype and try to resolve it there. So properties are first resolved in the actual object, and then in the prototype.

<script language="JavaScript">
  var driverslicense1 = {firstname :"Delois", lastname:"Price"};
    driverslicense1.__proto__.show = function(){
       console.log("Licensee: "+this.firstname + " " + this.lastname);
    }
  driverslicense1.show();
</script>

In the code above, the show() function was removed from the actual object and added to the prototype for that object. When we tried to execute the show() function, JavaScript searched the object first for the function, and then the prototype for that object. The prototype is now responsible for providing the show() function. The Prototype object is just an object. It can be treated like any other object. It can be modified or it can be created from scratch. JavaScript will automatically create a prototype when you create an object, but we can choose to create our own object and assign it to the __proto__ property. By creating our own object, we have a bit more explicit control of the properties included. The following example creates a new object and assigns it to the __proto__ property of the driverslicense1 object:

<script language="JavaScript">
  var driverslicense1 = {firstname :"Delois", lastname:"Price"};
    driverslicense1.__proto__={show :function(){
       console.log("Licensee: " + this.firstname + " " + this.lastname);
    }}
  driverslicense1.show();
</script>
Prototype Object

[click for larger image]

Creating our own prototype lets us use any object as the prototype. The realization that __proto__ is just a normal object and we are able to do normal “object” stuff with it allows us to use it to solve the earlier code reuse problem. In the example below, we simply assign the prototype from driverlicense1 to the __proto__ property of driverslicense2. Now both instances of the driverslicense can share the implementation of the show method.

<script language="JavaScript">
  var driverslicense1 = {firstname :"Delois", lastname:"Price"};
  driverslicense1.__proto__={show :function(){
       console.log("Licensee: " + this.firstname + " " + this.lastname);
  }}
  driverslicense1.show();

  var driverslicense2 = {firstname :"Michael", lastname:"Bolton"};
  driverslicense2.__proto__= driverslicense1.__proto__;
  driverslicense2.show();
</script>

Of course if driverslicense2 happened to have its own property named show, then JavaScript would resolve that property first and not use the “inherited” version of show that would have come from the prototype. In our example, the driverslicense1 prototype becomes a very powerful object for sharing properties across objects of a similar type. This concept is used very heavily when JavaScript is used to define an OO model using Constructors and inheritance. Keep an eye open for more on JavaScript Prototype Inheritance.


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 Train For 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 Gold 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

Baton 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.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.