The Constructor Pattern
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.
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!