5.15 Exercise: Function Factory and Constructor

In the last exercise, we used object literal syntax to initialize an address object. In this exercise, I want you to initialize an address object, first using a factory function and then using a constructor function. So your exercise is to write two different functions, one is a factory function, the other is a constructor function to initialize an address object. So go ahead and do this exercise and when you're done come back and continue looking at the correction. So I'm going to start with the factory function first, so factory functions simply return a new object, here we can call this createAddress function we have to give it three parameters, street, city and postcode, and here we simply return a New object with three properties, street, which we set to the street argument that we received. As I told you before, if the key and the value are the same, we can make our code cleaner by deleting the value, so in this value, we'll have these three properties. So this is our factory function, and we can just create a new address like this. So instead of using the object literal syntax, we call createAddress and give it these three values. Now let's record the address in the console to make sure it works. Here we have a new object, with these three properties. Now let's move on to the constructor function. So, constructor function. As I told you before, constructor functions have a different naming convention, so instead of the camelCase notation that we use in factory functions. Here we use PascalCase notation, so the first letter of the first word must be capitalized. So we'll call this function address. Again, we're going to pass three parameters, now here instead of returning an object, we're going to use the keyword this, to initialize this new object, so this. street We put this in the street argument then this. city and finally this. zip code. Now, to create a new address object using this constructor function, we use the new operator here and call our constructor function. Again, we pass in these values. And we connect this address object in the console. So save the changes and we get the exact same object. So the purpose of this exercise was to help you become familiar with the syntax for creating factory and constructor functions. In the next exercise, we will work with blog publishing objects.