The Basics of JavaScript Prototypes

I notice that a lot of beginning JavaScript programmers struggle with the concept of function prototypes and use them without understanding their purpose. Being one of the coolest features of JavaScript, I think that it’s pretty important to get a good grasp on what function prototypes are and what they are used for.


Before we begin, lets define a simple constructor for our example.

function Cat(name) {
    this.name = name;
    this.meow = function() {
        console.log(this.name);
    };
}

A prototype is a type of recipe for an object. Almost every JavaScript object has a prototype, and from these prototypes the objects inherit a bunch of shared properties and methods. This is where the power of the prototype object lies.

In the above example, we declared the constructor for a class called Cat that contains a single property, name, and a method that prints the cat’s name to the console window. Every time that we use this constructor to create an instance of the Cat object, that instance gets its own meow() method. This seems incredibly inefficient, as each individual instance contains its own method, rather than having a shared method across all instances. Most of the time methods do the same thing for all instances of an object, so there’s no reason for each one to have its own method. How do we create a shared method for every Cat instance? Prototypes.

A better version of the above code involves using a prototype for the meow() method.

function Cat(name) {
    this.name = name;
}

Cat.prototype.meow = function() {
    console.log(this.name);
};

With this new Cat constructor, we define meow() on the prototype, rather than the constructor itself. Creating an instance of the Cat object works in exactly the same way, even though meow() is now a prototype property.

Advertisements
The Basics of JavaScript Prototypes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s