One thing that is helpful to learn when programming in JavaScript is that nearly everything is an object. We can then use objects to create other objects. Sort of like a copying of the data. It is not a complete “copy and paste”, which I will blog about later, but what I wanted to concentrate on in this post is what this functionality gives us.
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"));
Notice the “new” keyword. This tells JavaScript, “Hey, I am creating something new here. In fact, it is a new instance of the Blog constructor object. So copy all of the necessary stuff for me.”
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.
Happy Coding!
Clay Hess