The Constructor Pattern

I’m currently reading Addy Osmani’s book Learning Javascript Design Patterns. I just finished my Q1 project I realize that I’m getting better with my Javascript fundamentals, but there isn’t a very strategic structure to any of the code that I’m writing. I’m doing my best to follow the best practices of Javascript, but I often have intuition that suggests there is a better way to write the code that I’m working on. My instructor recommended this book so here we are. I’m on my break week reading a book about design patterns. If you would have read that sentence to me two years ago I would have gotten a pretty good laugh out of it, but here we are and I’m loving every minute of it. I’m sure there’s a life lesson in there somewhere, but I’ll let you be the judge of that.

Let’s talk about the constructor pattern. What is a constructor in Javascript? A constructor is basically a function that constructs or creates an object.

Above you see an example of how a constructor is created and used. If we’re going to be creating a lot of objects with similar properties then this is the tool/pattern for the job. We can define the constructor one time and then we can reuse it over and over again to create new people objects just like we did on line 11 in the example above.

What if we wanted to add a method on this object that we can use to print out each person’s name in a more human readable format?

One way we could do this is to define the method on our original constructor like the example below.

The problem with this is that every time we create a new person we are creating a new method that lives on their instance of the Person object. Another way to say this is that each new instance will not “inherit” that method. Instead they are re-creating it each time. One of the core principles of programming is referred to as “DRY” or don’t repeat yourself. This violates that principle. There is a better way to achieve this without repeating ourselves. Functions in Javascript have a property called prototype. When we create a constructor all of it’s properties are available to each new instance that we create. So how do we add a prototype property to our Person constructor?

Above is the proper way to add a prototype to our Person constructor. As you can see the final result of our console.log() is the same, but there’s one major difference. Now we are only creating the toString() method one time which keeps us from violating the “DRY” principle we just talked about. Now each new instance of Person will inherit the toString() prototype and we can use it on each of them without re-creating it. Problem solved!

That was a simplified description of constructors and the constructor pattern, but hopefully you are starting to see how it can be useful. Maybe you have some code that you can refactor using this pattern? I know I do!

Show your support

Clapping shows how much you appreciated Jon Ramer’s story.