Coding In The Dark Challenge…Featuring Constructors/Cookie Cutters

Image result for coding in the dark

Our professor gave us a challenge. Go through code that she wrote and modify it and make it better. She wanted us to go through the code and make it modular and reusable.

We did this by using everything we’ve learned so far and the most important one would be constructor functions.

Here’s an example of a constructor.
Side note… When a function is defined for an object it’s called a method

Here we are looking at the syntax. Similar to objects we have properties and methods. However we can see that we are using dot operators/accessor to retrieve the properties/key and assign a value to it for this instance of the objects creation. That’s why we use the key word “this” as it refers to where we are currently at the time the code executes. (More on accessors… when we call a property/key or a function that was defined in an object in another piece of code we can access the defined value/function.)

This is an example of creating the new instance (using the keyword new) of the object based on the template/constructor we defined above.

We started to learn about how this can make things flexible and template-like we can so reuse it. Constructors are very much like objects, but why we would want to use it instead of an Object? This is because if we wanted to use more than one object, we would have to redefine all of the properties and methods every time we wanted to make another. This is why we can compare it to a cookie cutter, it’s a template.

This was a part of the code we were asked to improve…above you can see the way I made a constructor function to replace these hard coded values and functionality

Before this we have been using up to now was an example of procedural programming. Writing a program this way will only work for that program and if we wanted to change or add things, we might have to rewrite the whole thing. Using constructors is a starting point to modularity with Object Oriented Programming. We want to try to step away from hard coding values in and make things dynamic and flexible.

Leave a comment