Constructing Constructor Functions

When you are first learning JavaScript, you will be introduced to two ubiquitous language features: functions and objects. As you begin to experiment with creating objects, you may find is useful to implement a simple function to create commonly used object types. For instance, here’s a function that will create an instance of a photo object:

function createPhoto(url, date, caption) {
    return {
        url: url,
        date: date,
        caption: caption
    };
}

var photo = createPhoto("rabbits.jpg", "05/10/2015",
                       "Someone's been eating my radishes.");

Using such a function ensures that every photo object has the same set of properties, and this example provides an excellent starting point for understanding JavaScript constructor functions. What if we make a few minor changes…

function initPhoto(newPhoto, url, date, caption) {
    newPhoto.url = url,;
    newPhoto.date = date;
    newPhoto.caption = caption;
}

var photo = {};
initPhoto(photo, "rabbits.jpg", "05/10/2015",
          "Someone's been eating my radishes.");

Instead of creating the object within our function, we create the object and pass it to the function for initialization. But the end result is the same. We have a new object with all the expected properties attached. This is essentially how constructor functions work, but the syntax is slightly different.

function Photo(url, date, caption) {
    this.url = url;
    this.date = date;
    this.caption = caption;
}

var photo = new Photo("rabbits.jpg", "05/10/2015",
                      "Someone's been eating my radishes.");

When we use the new keyword, JavaScript creates a new object and passes it into the constructor function. However, instead of appearing in the function’s argument list, it’s accessed using the this keyword. By convention, constructor functions are capitalized to distinguish them from other functions.

Once you feel comfortable with how constructor functions are used to initialize new objects, you can begin to experiment with some of their other benefits – prototypes.

1 comment for “Constructing Constructor Functions

  1. June 20, 2015 at 4:40 pm

    You’ve got to love spammers who haven’t quite mastered the English language. Here’s an excerpt from a comment that was left on this post:

    “I don’t even know the way I finished up right here, but I believed this post used to be good.”

    My apologies to anyone who didn’t get to read it back when it was good.

Leave a Reply

Your email address will not be published. Required fields are marked *