Menu

A quick look at prototypes in JavaScript

A quick look at prototypes in JavaScript

All JavaScript objects inherit properties and methods from a prototype. Prototypes are the mechanism by which JavaScript objects inherit features from one another. The prototype property can be used to add methods to existing constructors. And if that sounds confusing to you, then you are in the right place. Follow along as I attempt to break those few lines apart into a more coherent set of sentences.

Let's start with objects

Before we dive in to the prototype property, we have to first discuss objects in JavaScript.

Objects are collections of properties (and methods/functions) that can be assigned to a variable and modified as needed with newer properties or by removing properties. A quick example would be the following:

var person = {
    firstName: 'Walt',
    title: 'thatsoftwaredude'
};

In this example, the person variable, while an individual entity, contains multiple pieces of data. You can think of them as 'many variables' in one. Objects are highly beneficial when we need to package up data into one easy to reference package. You can also add functions inside of objects if needed, which are many times referred to as 'methods'.

var person = {
    firstName: 'Walt',
    title: 'thatsoftwaredude',
    sayHi: function(){
         console.log('hi');
    }
};

You can also create object constructors. What are object constructors? Think of them as blueprints specifying which properties an object can contain. Why do we need blueprints? Well, if in the example above you needed to create another person object, you would essentially need to take a peek at the first person object to see which properties were used there. If, however, you have a pre-defined template or blueprint generated, you don't have to worry about issue. And most coding editors will graciously show you all of the included properties and methods once you type the '.' operator.

object constructors

And in case that list bit was still confusing, here is a further breakdown. Object constructors are generated using functions in JavaScript to give a pseudo OOP type definition, and looks something like the following:

function Person(first, title)
{
    this.firstname = first;
    this.title = title;
}

This creates a blueprint for a Person object, but does not in itself create an object. That can be done with the following:

var person = new Person('walt', 'thatsoftwaredude');
var person2 = new Person('bob', 'the dude');

Notice the benefit of not having to remember which properties the Person object requires. We can simply use the constructor syntax to create brand new Person objects as we need them.

So what does this have to do with prototypes? Great question.

Once an object constructor is generated, we cannot add new properties to it. What does that mean? That the following is not allowable:

Person.degree = 'Bachelors Degree';

If you wanted to add more properties to the Person object, you need to update the original Person constructor from above. And this is where the prototype property comes into play.

How to use the prototype property

As mentioned above, every object inherits from Object.prototype. And we can use this prototype property to add new properties and methods to an already defined function. And we can do so as such:

Person.prototype.hairColor = "Gandalf grey";

At this point, every other declaration of a Person will also receive this new property addition. So if we had 10 person objects declared, then we would be able to set the hairColor property of those going forward.

Compare this to the non constructor approach, in which we would have to go in and manually add that property to each one or it would be found to be undefined.

Prototypes also allow us to add new properties and methods to already existing object types, such as Date and Math which are built in to the JavaScript language.

Date.prototype.newProperty = 'hello world';

While you have the ability to do this, it is normally not recommended to update currently existing JavaScript object types. But this is one of the main standout points in working with the prototype model. That we can dynamically update object type definitions, if we need to, and the prototype chain will ensure that all of the objects of that type contain these properties.

There's a bit more complexity and intrigue when it comes to working with prototypes, which I'll cover on a future post. But for anyone who has heard the term and never quite knew how to use it or just what it was, I hope you found this post helpful.

If you enjoyed this post or found it helpful, leave a like down below as it helps me in figuring out which topics to write about next.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment