Tutorial

Understanding Prototypes and Inheritance in JavaScript

Updated on August 26, 2021
Understanding Prototypes and Inheritance in JavaScript

Introduction

JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended. This is known as prototypical inheritance and differs from class inheritance. Among popular object-oriented programming languages, JavaScript is relatively unique, as other prominent languages such as PHP, Python, and Java are class-based languages, which instead define classes as blueprints for objects.

In this tutorial, we will learn what object prototypes are and how to use the constructor function to extend prototypes into new objects. We will also learn about inheritance and the prototype chain.

JavaScript Prototypes

In Understanding Objects in JavaScript, we went over the object data type, how to create an object, and how to access and modify object properties. Now we will learn how prototypes can be used to extend objects.

Every object in JavaScript has an internal property called [[Prototype]]. We can demonstrate this by creating a new, empty object.

let x = {};

This is the way we would normally create an object, but note that another way to accomplish this is with the object constructor: let x = new Object().

The double square brackets that enclose [[Prototype]] signify that it is an internal property, and cannot be accessed directly in code.

To find the [[Prototype]] of this newly created object, we will use the getPrototypeOf() method.

Object.getPrototypeOf(x);

The output will consist of several built-in properties and methods.

Output
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, …}

Another way to find the [[Prototype]] is through the __proto__ property. __proto__ is a property that exposes the internal [[Prototype]] of an object.

It is important to note that .__proto__ is a legacy feature and should not be used in production code, and it is not present in every modern browser. However, we can use it throughout this article for demonstrative purposes.

x.__proto__;

The output will be the same as if you had used getPrototypeOf().

Output
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, …}

It is important that every object in JavaScript has a [[Prototype]] as it creates a way for any two or more objects to be linked.

Objects that you create have a [[Prototype]], as do built-in objects, such as Date and Array. A reference can be made to this internal property from one object to another via the prototype property, as we will see later in this tutorial.

Prototype Inheritance

When you attempt to access a property or method of an object, JavaScript will first search on the object itself, and if it is not found, it will search the object’s [[Prototype]]. If after consulting both the object and its [[Prototype]] still no match is found, JavaScript will check the prototype of the linked object, and continue searching until the end of the prototype chain is reached.

At the end of the prototype chain is Object.prototype. All objects inherit the properties and methods of Object. Any attempt to search beyond the end of the chain results in null.

In our example, x is an empty object that inherits from Object. x can use any property or method that Object has, such as toString().

x.toString();
Output
[object Object]

This prototype chain is only one link long. x -> Object. We know this, because if we try to chain two [[Prototype]] properties together, it will be null.

x.__proto__.__proto__;
Output
null

Let’s look at another type of object. If you have experience Working with Arrays in JavaScript, you know they have many built-in methods, such as pop() and push(). The reason you have access to these methods when you create a new array is because any array you create has access to the properties and methods on the Array.prototype.

We can test this by creating a new array.

let y = [];

Keep in mind that we could also write it as an array constructor, let y = new Array().

If we take a look at the [[Prototype]] of the new y array, we will see that it has more properties and methods than the x object. It has inherited everything from Array.prototype.

y.__proto__;
[constructor: ƒ, concat: ƒ, pop: ƒ, push: ƒ, …]

You will notice a constructor property on the prototype that is set to Array(). The constructor property returns the constructor function of an object, which is a mechanism used to construct objects from functions.

We can chain two prototypes together now, since our prototype chain is longer in this case. It looks like y -> Array -> Object.

y.__proto__.__proto__;
Output
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, …}

This chain is now referring to Object.prototype. We can test the internal [[Prototype]] against the prototype property of the constructor function to see that they are referring to the same thing.

y.__proto__ === Array.prototype;            // true
y.__proto__.__proto__ === Object.prototype; // true

We can also use the isPrototypeOf() method to accomplish this.

Array.prototype.isPrototypeOf(y);      // true
Object.prototype.isPrototypeOf(Array); // true

We can use the instanceof operator to test whether the prototype property of a constructor appears anywhere within an object’s prototype chain.

y instanceof Array; // true

To summarize, all JavaScript objects have a hidden, internal [[Prototype]] property (which may be exposed through __proto__ in some browsers). Objects can be extended and will inherit the properties and methods on [[Prototype]] of their constructor.

These prototypes can be chained, and each additional object will inherit everything throughout the chain. The chain ends with the Object.prototype.

Constructor Functions

Constructor functions are functions that are used to construct new objects. The new operator is used to create new instances based off a constructor function. We have seen some built-in JavaScript constructors, such as new Array() and new Date(), but we can also create our own custom templates from which to build new objects.

As an example, let’s say we are creating a very simple, text-based role-playing game. A user can select a character and then choose what character class they will have, such as warrior, healer, thief, and so on.

Since each character will share many characteristics, such as having a name, a level, and hit points, it makes sense to create a constructor as a template. However, since each character class may have vastly different abilities, we want to make sure each character only has access to their own abilities. Let’s take a look at how we can accomplish this with prototype inheritance and constructors.

To begin, a constructor function is just a regular function. It becomes a constructor when it is called on by an instance with the new keyword. In JavaScript, we capitalize the first letter of a constructor function by convention.

characterSelect.js
// Initialize a constructor function for a new Hero
function Hero(name, level) {
  this.name = name;
  this.level = level;
}

We have created a constructor function called Hero with two parameters: name and level. Since every character will have a name and a level, it makes sense for each new character to have these properties. The this keyword will refer to the new instance that is created, so setting this.name to the name parameter ensures the new object will have a name property set.

Now we can create a new instance with new.

let hero1 = new Hero('Bjorn', 1);

If we console out hero1, we will see a new object has been created with the new properties set as expected.

Output
Hero {name: "Bjorn", level: 1}

Now if we get the [[Prototype]] of hero1, we will be able to see the constructor as Hero(). (Remember, this has the same input as hero1.__proto__, but is the proper method to use.)

Object.getPrototypeOf(hero1);
Output
constructor: ƒ Hero(name, level)

You may notice that we’ve only defined properties and not methods in the constructor. It is a common practice in JavaScript to define methods on the prototype for increased efficiency and code readability.

We can add a method to Hero using prototype. We’ll create a greet() method.

characterSelect.js
...
// Add greet method to the Hero prototype
Hero.prototype.greet = function () {
  return `${this.name} says hello.`;
}

Since greet() is in the prototype of Hero, and hero1 is an instance of Hero, the method is available to hero1.

hero1.greet();
Output
"Bjorn says hello."

If you inspect the [[Prototype]] of Hero, you will see greet() as an available option now.

This is good, but now we want to create character classes for the heroes to use. It wouldn’t make sense to put all the abilities for every class into the Hero constructor, because different classes will have different abilities. We want to create new constructor functions, but we also want them to be connected to the original Hero.

We can use the call() method to copy over properties from one constructor into another constructor. Let’s create a Warrior and a Healer constructor.

characterSelect.js
...
// Initialize Warrior constructor
function Warrior(name, level, weapon) {
  // Chain constructor with call
  Hero.call(this, name, level);

  // Add a new property
  this.weapon = weapon;
}

// Initialize Healer constructor
function Healer(name, level, spell) {
  Hero.call(this, name, level);

  this.spell = spell;
}

Both new constructors now have the properties of Hero and a few unqiue ones. We’ll add the attack() method to Warrior, and the heal() method to Healer.

characterSelect.js
...
Warrior.prototype.attack = function () {
  return `${this.name} attacks with the ${this.weapon}.`;
}

Healer.prototype.heal = function () {
  return `${this.name} casts ${this.spell}.`;
}

At this point, we’ll create our characters with the two new character classes available.

characterSelect.js
const hero1 = new Warrior('Bjorn', 1, 'axe');
const hero2 = new Healer('Kanin', 1, 'cure');

hero1 is now recognized as a Warrior with the new properties.

Output
Warrior {name: "Bjorn", level: 1, weapon: "axe"}

We can use the new methods we set on the Warrior prototype.

hero1.attack();
Console
"Bjorn attacks with the axe."

But what happens if we try to use methods further down the prototype chain?

hero1.greet();
Output
Uncaught TypeError: hero1.greet is not a function

Prototype properties and methods are not automatically linked when you use call() to chain constructors. We will use Object.setPropertyOf() to link the properties in the Hero constructor to the Warrior and Healer constructors, making sure to put it before any additional methods.

characterSelect.js
...
Object.setPrototypeOf(Warrior.prototype, Hero.prototype);
Object.setPrototypeOf(Healer.prototype, Hero.prototype);

// All other prototype methods added below
...

Now we can successfully use prototype methods from Hero on an instance of a Warrior or Healer.

hero1.greet();
Output
"Bjorn says hello."

Here is the full code for our character creation page.

characterSelect.js
// Initialize constructor functions
function Hero(name, level) {
  this.name = name;
  this.level = level;
}

function Warrior(name, level, weapon) {
  Hero.call(this, name, level);

  this.weapon = weapon;
}

function Healer(name, level, spell) {
  Hero.call(this, name, level);

  this.spell = spell;
}

// Link prototypes and add prototype methods
Object.setPrototypeOf(Warrior.prototype, Hero.prototype);
Object.setPrototypeOf(Healer.prototype, Hero.prototype);

Hero.prototype.greet = function () {
  return `${this.name} says hello.`;
}

Warrior.prototype.attack = function () {
  return `${this.name} attacks with the ${this.weapon}.`;
}

Healer.prototype.heal = function () {
  return `${this.name} casts ${this.spell}.`;
}

// Initialize individual character instances
const hero1 = new Warrior('Bjorn', 1, 'axe');
const hero2 = new Healer('Kanin', 1, 'cure');

With this code we’ve created our Hero constructor with the base properties, created two character constructors called Warrior and Healer from the original constructor, added methods to the prototypes and created individual character instances.

Conclusion

JavaScript is a prototype-based language, and functions differently than the traditional class-based paradigm that many other object-oriented languages use.

In this tutorial, we learned how prototypes work in JavaScript, and how to link object properties and methods via the hidden [[Prototype]] property that all objects share. We also learned how to create custom constructor functions and how prototype inheritance works to pass down property and method values.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Tutorial Series: How To Code in JavaScript

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

About the authors


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
7 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I am just learning about prototypes, but one part of this didn’t seem right to me, and after trying out some things I think I can explain what I mean. It’s this part:

// Link prototypes and add prototype methods
Warrior.prototype = Object.create(Hero.prototype);
Healer.prototype = Object.create(Hero.prototype);

This isn’t really linking the objects, it’s more like replacing them. The point of the prototype chain as far as I can tell is that you can link them to form a kind of inheritance, without losing attributes, but this will lose them. Here’s what I mean:

function Hero(name, level){
    this.name = name;
    this.level=level;
}

function Healer(name, level, spell){
    Hero.call(this, name, level);
	this.spell = spell;
}

Hero.prototype.greet = function(){return "I am " + this.name}
Healer.prototype.heal = function(){return this.name + " casts " + this.spell}

var healer = new Healer("Pyro", 126, "Resta");

healer.heal()
// "Pyro casts Resta"
healer.greet() // undefined, as expected, not linked yet
// VM1872:1 Uncaught TypeError: healer.greet is not a function

// Now "link" the prototypes
Healer.prototype = Object.create(Hero.prototype)

healer.greet() // healer linked to old Healer prototype still, have to construct it again to pick up the change
// VM1872:1 Uncaught TypeError: healer.greet is not a function

healer = new Healer("Pyro", 126, "Resta");
healer.greet()
// "I am Pyro"
healer.heal() // oops
// VM2045:1 Uncaught TypeError: healer.heal is not a function

healer.constructor // Thinks its constructor is hero's
// ƒ Hero(name, level){
//     this.name = name;
//     this.level=level;
// }

So, as you can see, swapping out prototypes can lead to some really strange behavior. I found this out the hard way trying examples in this article.

Now, if you changed my example to define methods on Hero’s prototype first, then copy Hero’s to Healer’s, then define new methods on Healer’s, that works, but that is unnecessarily finicky seems to defeat the purpose of inheritance.

Another problem with the way in the article is that “Healer.prototype” begins with a reference to the “Healer” constructor. When you override the “prototype” property, “Healer.prototype.constructor” now point’s to “Hero’s” constructor. This makes things pretty ambiguous, because now healer, created with Healer’s constructor, thinks its constructor is actually Hero’s.

Rather, I think you should set the [[Prototype]] property of Healer’s prototype to point to Hero’s prototype. See this example for what seem like a better way to me:

function Hero(name, level){
    this.name = name;
    this.level=level;
}

function Healer(name, level, spell){
    Hero.call(this, name, level);
	this.spell = spell;
}

Hero.prototype.greet = function(){return "I am " + this.name}
Healer.prototype.heal = function(){return this.name + " casts " + this.spell}

var healer = new Healer("Pyro", 126, "Resta");

healer.heal()
// "Pyro casts Resta"
healer.greet() // undefined, as expected
// VM1872:1 Uncaught TypeError: healer.greet is not a function

// Instead of setting Healer.prototype, we're setting [[Prototype]] of Healer.prototype
Object.setPrototypeOf(Healer.prototype, Hero.prototype);

healer.greet() // This is now found, by traversing the prototype chain. You don't have to reassign healer. 
// "I am Pyro"
healer.heal() // healer's prototype is still Healer.prototype so this is fine
// "Pyro casts Resta"

// because prototypes are linked properly, children of Hero automatically obtain new methods defined on Hero
Hero.prototype.charge=function(){return "CHARGE!!"}
healer.charge() // didn't need to change anything on healer object or Healer function
// "CHARGE!!"
healer.constructor // healer still has proper constructor
// ƒ Healer(name, level, spell){
//     Hero.call(this, name, level);
//	this.spell = spell;
// }

This seems to work a lot better: the order in when you declare things doesn’t matter, Healer’s prototype information is preserved. When you look at the structure of the object in the console, you see what looks more like proper inheritance. Let me know what you think.

Nice content! Very helpful :)

Just a heads-up: I guess “Object.setPropertyOf()” should be “Object.setPrototypeOf()” here

We will use Object.setPropertyOf() to link the properties in the Hero constructor to the Warrior and Healer constructors, making sure to put it before any additional methods.

Uma delicia de conteudo. mulher é demais

Also, it would be quite nice if you would explain the exact difference between prototype and __proto__ properties. It can be a source of greate confusion for the beginners. Especially when encountered in expressions like Warrior.prototype.__proto__ = Hero.prototype.

Hey! There is a slight bug in your example code.

Warrior.prototype = Object.create(Hero.prototype) would actually replace all of the contents of the original Warrior prototype. Methods can be restored with proper sequence of statements in code. But what cannot be restored is a constructor property, which in turn is used by things like instanceof.

This could result into something like:

const warrior = new Warrior();
console.log(warrior instanceof Hero); // true
console.log(warrior instanceof Warrior); // false

That is, the prototype chain is broken, which is most probably not what we intended.

What one should do instead is:

Warrior.prototype.__proto__ = Object.create(Hero.prototype);

That would properly link Warrior to Hero’s whatever prototype chain correctly.

Also, you can safely get rid of Object.create() because this intermediate empty object doesn’t add any value.

So finally constructor function prototype’s linkage would look something like this:

Warrior.prototype.__proto__ = Hero.prototype;

In fact, if you look inside objects created with new ES2015 class syntax from class hierarchies using extend, you will find out that prototypes are linked exactly that way.

This article is not as good as the others. It’s a bit confusing, because the author doesn’t explain the concept or prototyping and the reasons behind it.

Could you please put this part a bit more clear ? - “This prototype chain is only one link long. x -> Object. We know this, because if we try to chain two [[Prototype]] properties together, it will be null.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel