5.17 Exercise: Constructor Function

In this exercise, we will again use a constructor function to create a publication object. But this constructor object is a little different from the constructor function you saw earlier. Imagine we are building a blog engine, the user is writing an article, but they haven't published it yet, what do you think the constructor function should look like? So spend a few minutes on this exercise, when you're done, come back and continue looking at the fix. Let's start by creating this constructor function, we'll call it post, with a capital P here So what parameters do we need here? Obviously we need the title, the body and the author, but we don't need the number of views, because the first time we create a post, the views should be set to zero, and every time we display this post, we increment that value. So views are not something we want to pass in here, we want to use a default value of zero, when initializing this publishing object. The same goes for the comments property. For a new post that hasn't been published yet, we have no comments, so we don't want to add a comments setting here. The same goes for the isLive property. We want to set this to false by default, so there's really no need to add an extra parameter in this function. So we should aim to have functions with fewer parameters. The more parameters a function has, the harder it becomes to use So here we'll set this. title to the .title argument. The same goes for the body, and the author property. Now, for the views, I'm going to initialize this to 0, likewise we're going to initialize the comments to an empty array, so in the future, we can add new objects to this array, and then finally we set isLive to false . Now, instead of initializing this publishing object here, we'll call our constructor function, we'll pass in the title, the body and the author, and finally save this to the console. So we can see the author, body and title properties are initialized according to the values we passed here. But the author properties have default values. So the comments are initialized to an empty array. isLive is false and views are 0. That's it for this little exercise at the end of the section on objects in JavaScript, let's meet again for the next section where we'll see the arrays