We can have an object called a constructor wherein we set up the blueprint for our object. I will go into details of a constructor in a future post. In this one, I simply want you to grasp the power and ease of code reuse with objects within an object and how that allows us to build robust code.
For example, say we have a constructor entitled, “Blog”. Notice the caps…all constructors are supposed to be capitalized. This is not enforced by the language but is a generally accepted convention. Within this Blog constructor, there are two properties…one for holding a date object and one for holding the string of the actual post content.
We can then create an individual blog entry by utilizing the Blog constructor object. It might look like this…
// Create a variable to hold a blog entry var blogEntry = new Blog(“Something interesting written here.”, new Date("10.31.2016"));
As I stated earlier, the Blog constructor took two properties…date and string. We can create/pass those along as parameters for the constructor. We now have an individual blog entry.
So why is this important? Within the constructor, we can encapsulate any logic specific to that object…built-in methods, properties, etc. This allows for easier code maintenance and maintains our logic and structure.