What do you want to learn?
Skip to main content
by Susan Simkins
Start CourseBookmarkAdd to Channel
Table of contents
Introduction and Project Overview
Introduction and Project Overview
In this lesson we'll learn how to create objects. In this volume we'll continue to work out of Brackets Text Editor just like we did when we finished up in Volume 2. So to open our files for this lesson we just want to come over here once again to our Files pane and we want to select our drop down arrow, come down to Open Folder and we also want to make sure we navigate to our project file for this lesson. So we're in Lesson 2 so we'll open 02Begin, select our folder and then we'll double-click on our main .js file. Should bring it up into our working files which you can find in our Scripts folder. So let's say we want to model something using our code or describe something. Lets say I'm drinking my coffee and I find the perfect combination of flavors and temperature and brand maybe and I want to remember this at a later date. Using the syntax we know so far how could we model something like my coffee which you can see right here. We have our little CSS coffee mug with a little coffee spill since that seems to happen to me quite often. So we might use something, we know we can use variables to store information so lets go ahead and use variables to kind of describe our coffee here. So we want to use that var keyword and then we want to give it a name. So maybe I want to call it variable coffee flavor. I'm just going to use camelcase for this. And then we need our assignment operator or equals sign to assign a value and then let's say my flavor is espresso so I add that in the form of a String. And then we'd add our semicolon. And let's say we want to describe its temperature so var coffee, whoops if I can type correctly, temperature... would be maybe piping hot. And then maybe I wanted something else like the perfect size I remember the amount of ounces I like in my coffee might be something like I guess it wouldn't be a String but a number, maybe 100 ounces or 1000, lots of coffee. And then maybe we want to remember, do we add milk to our coffee? We might finish up by adding one called coffee milk and then maybe we'd use a Boolean for this and maybe I like milk in my coffee so I might set that to true. So we have a collection of things that's describing our coffee but what if we wanted to use all of these together somewhere else in our code? Well, using what we know so far we could use something like an array but that doesn't quite make sense. What if we want to easily be able to pick out something that describes something about our coffee? Maybe I want to be able to easily refer to its temperature, the amount of ounces it has or whether it has milk? Well one thing we know about arrays is we have to reference an array position so that's not ideal if we want to remember a specific thing and be able to refer to it by name like we have here. And another downfall of this is we have no way of identifying that these belong together. These are all treated individually in our code and there's no association here between the relationship of our description. So the way we can model things like this using code is by creating whats called an object. So lets go ahead and create an object and see how we can accomplish the same thing in a slightly different way. So I'm going to press Enter here just so we can add some separation between our variables and our object. And just like with a variable we start by storing our object in a variable because that's really how we remember values or the things of our code. So we need that var keyword and then we want to give our object a name so maybe I want to call it my coffee since that's what we're creating here or describing. And then we need our assignment operator and if you think back to everything we've learned so far one way we've been associating code together as in this all goes together is by creating a code block and that's exactly what we do when we create an object is we just have some curly braces that tell our code that this all belongs to our object. And we add every description about our object in the form of what's called a property. So lets add a property which is going to describe our object. So lets say we wanted to describe the flavor just like we did with our first variable we just give it a name which is called a key when we're talking about an object. So we're going to add our flavor and then rather than using an assignment operator which is storing something we're actually kind of describing something. So the syntax is a little bit different here and we use a colon and then we want to add whatever value we want here just like we would with a variable. So the flavor we have is espresso so we're just going to go ahead and add that. And then we're not creating a statement like we were up here, we're actually describing a list of properties since our object is a list of key value pairs, a list of properties. So just like we would in an array we comma separate something like that when we're storing a list of values. So we add our comma and then we can add our next property. So maybe we want to add the temperature. And we want to describe it as being piping hot. We add our comma, add our next property. Say maybe we want to say ounces would be 100 and then maybe milk, we want to add true. And one thing you'll notice here is I didn't add a comma after our last value here and that's because if we add a trailing comma, so if we do't have anything after this then in Internet Explorer we're gonna get an error. So we just leave that last comma off just so we know that our code is going to work in those older versions of IE. So I'm going to go ahead and delete these extra spaces here and the last thing we need is a semicolon after our last bracket. So just like when we're creating a variable here and giving it a value we're doing exactly the same thing here. We're creating a variable, we're giving it a name and then we're storing an object in our variable so we have our variable and we finish it off with a semicolon. So what if we want to talk about the properties we added in our object? Well we can use something called dot notation to reference anything inside of here, any of our properties. So the first thing we want to do is use our name of our object, so mycoffee, and we can just add a dot and then whatever we want to access inside of our object. So we can see we have flavor, temperature, ounces and milk and our code is recognizing all these as properties and pulling it up as options when we talk about the mycoffee object we've just created. So maybe we want to find out or remember later how many ounces were in our coffee. It's going to say mycoffee.ounces and then add our semicolon here. So lets go ahead and use an alert to alert mycoffee.ounces. So just alert and then add our object and our property inside those parenthesis. And if I hit Control S to save this you can see over here we're getting an alert box with our results. We're seeing 100 which is exactly the value we have stored inside of our object. So I can say okay thank you for that little information and you can kind of see here how much different this is than trying to describe it in just a series of variables. These are in no way associated with one another. There's nothing in our code to indicate that we're describing our coffee and they're just kind of loosely floating around versus here we can easily talk about these by name. We can maybe, if we needed to know full list of everything inside of here we are able to do that. And things of that nature. So now that we have learned how to create our first object and how to access its properties in our next lesson we're going to learn another way of accessing properties in an object and also about something called a method.
In this lesson we'll learn about adding methods to an object. in our last lesson we learned about objects or how we can use this object syntax to model real life objects using code when we modeled our coffee here. So what if we wanted to add something other than a property or a pair of a key which consists of a name and then a value? Well we can add something called a method to an object which sounds like another complicated term to learn but all it really is is adding a property in which the value is a function. So lets go ahead and add a method to our object and see what this does. So since we're going to be adding another property to our coffee object here after last property, our milk and then our Boolean value of true we need to add another comma and then we just use the same syntax so we want to give it a key or a name and we're going to call this maybe reheat. Maybe we want to be able to perform a command that reheats our coffee if it's gotten cold. So lets just call it something common sense like reheat. We need our colon and then instead of a primitive value kind of thinking back to Volume One we remember primitive values are our most basic unit like a String a number or a Boolean. So for reheat we're going to use function as our value. So we're going to say function and we're not going to accept any parameters because we're just going to be reheating our coffee, it doesn't need to accept any arguments here. And then we need our curly braces. And inside of this, let's go ahead and think this out. So this purpose of our function is going to be reheat our coffee so we're going to say look at the temperature and set it back to be hot. But it doesn't make sense to run this if it's already hot. So first let's go ahead and put a check inside of our function to check our temperature and see if it's cold. So we're going to say if... and then our object so we want to say what are we targeting, if what is cold? So we want to tell it to look for mycoffee object and then we're going to be accessing a property of our object which we learned in our last lesson we could use dot notation. So first we want to name our object and then we just want to select whatever property we want to target, so we're going to chose this last one temperature so you could type that out or you could also select it from the drop down list it pulls up automatically for us. So you could also see that reheat here has now been added as a property of our coffee object. So I'm going to select that temperature. So if my coffee's temperature is equal to cold, then we need our second set of curly braces to tell our code what to do if it's cold and inside so we're going to use two spaces here to maintain that indentation and be consistent. We're going to say set it back to be hot again. So we're going to say mycoffee for our object and then what property we want to access so temperature, and set it to be piping hot again. So we use that single equal sign once again when we want to assign a new value to something and then we'll set it back to be piping hot. And then I'll add our semicolon and maybe also we want to have an alert here so we know that our function is working. So maybe we want to say if our coffee is now hot again and this function has been run then alert your coffee has been reheated and then our semicolon right there. And so lets go ahead and hit Control S to save this and you can see we get some issues down here but we're going to come back to these once again later in our course and learn what JSLint is. So I'm going to go ahead and exit out of this and right below here we're going to, first we need to set the temperature back to cold so we can see our function is working. So we're going to say set mycoffee, so our object, and then our property set it to cold using our single equal sign or our assignment operator and now it's cold but if you remember we need to invoke or call a function in order for it to run. We actually have to use that command to see that code being run so we want to use our command so we want to say mycoffee.reheat and then when we call a function or invoke a function you remember we need to add our parenthesis there like we see right here. Since we do't have any arguments we don't have to add anything inside so we just need our semicolon. So if we hit Control S to save we should be seeing our message that our coffee's been reheated. So I'm going to hit Control S to save and you can see that our method, our reheat method of our mycoffee object is now working. So this is really really cool. We've learned how to associate a function with a specific object which is called just a method. It's correct to call it both a function and a method but a method is more specific because by implication of using that term you understand that a method is associated with a specific object. So it gives it a better idea of the context and we want to make sure to use that term if it's inside of an object like we have here. And it turns out we've been using methods all along so for example, when we use console.log, log is actually a method of the console object. So there are already objects that have been created in our code. There are already things that are built into the language or things that have been created by the browser such as the console object. That way we already have things that we can use and we don't have to write it from scratch ourself. So this is really really cool, we've actually been using it all along and not realizing that we've been using objects and methods this entire time. So we can see console.log, we have our console object and then dot and then our method which we can tell is a method and not a key and just a primitive value pair because we get those parentheses there showing it is a function or a method. So this is really really cool and if that kind of threw you for a loop as we were going along wondering why we could use some functions without this little word and then a dot and then some needed it like our console.log and our mass.random, that's because they are associated with an object so we have to specify that object first. So now we've kind of come full circle and we can really understand what that is. And if you remembered in our last lesson we learned about dot notation I also mentioned that there's another way of accessing a property of an object as well. So if we wanted to say mycoffee.temperature and assign it cold as a value instead of piping hot we could use something called bracket notation instead. So right under here I could also say mycoffee is our object and then rather than using that dot there we use brackets notation. So we need straight brackets and then we add our property inside in the form of a String. So we'd say temperature and then our closing bracket and then we need our assignment operator and we can add something different like lukewarm maybe. And so now if we run this we shouldn't get our function working. So I'm going to hit Control S to save and you can see we're not getting an alert that our coffee has been reheated because first we've changed it to cold and we've also changed it to be lukewarm. And this syntax might be a little bit confusing looking but we can also kind of think of an object being similar to an array because an array if you remember from Volume 2 is a comma separated list of values. So an object is a list of key value pairs so we can access a property similar to how we would target a position in an array. Maybe if this was an array we might have mycoffee and then we use this straight bracket notation and maybe if we wanted to access temperature we would put in one there. If you remember, array position starts at zero so we'd have zero and then one. Now since this is an object this notation doesn't work but you can kind of see the similarities to that. So now that we've taken a look at objects, we learned about methods and also taken a look at some methods and objects we've been using this entire time in our next lesson we're going to continue to learn about objects and talk about a way to create multiple objects using the object constructor.
Object Literals and Object Constructors
In this lesson we'll learn how to create objects using an object constructor. Lets say we have our friends back from Volume Two. Lets create an object to represent our friend Mark using code. So if we wanted to represent him using an object we just use our var keyword, give it name like Mark and then use our assignment operator and open and close our curly brackets at our semicolon and add all of our properties and any methods we might need inside. So looking at Mark how can we describe him using our code? Just by looking here at our friend Mark there's two things I can really tell about him. I can tell that he has a name and also what color his shirt is as well. So lets add his name as a property. So I would say Mark's name and then a colon and then whatever value I want for that property. So his name is Mark. Then I add a comma and add any other properties we need, so if we wanted to say his t-shirt color we just say t-shirt color and then maybe that is something like navy blue. And since that's all we can really tell about him just by looking I'm just going to leave it at that. And remember if we have a list of properties inside of our object we don't add a trailing comma after our last property because it will throw up that error in older versions of Internet Explorer. So we go ahead and leave it off that way we can make sure we don't run into any of those errors. So I'm going to go ahead and delete the extra space and if we were to do the same thing for Lisa we might see something similar. Maybe we create our object for Lisa and then we'd add her properties inside so her name is Lisa and her t-shirt color would be something like red. But as we're objectifying our friends in a good way with our code I can see something in common between our objects. We can see that our friends have names and they have t-shirt colors as well. And if you think back to Volume Two, one principle we talked about was called DRY or Do Not Repeat Yourself when you're writing code. So when we're creating objects in this way we're creating what's called an object literal or creating and defining our object at the same time which is called creating an instance of an object. So lets look at another way we can create an object and see how this might be a little bit different than using an object literal. So right below here we're going to create what's called an object constructor which uses a function to create kind of a template for an object. So if you remember we create functions using the function keyword then we need to give our function a name and when we're creating an object constructor or a function that creates objects it's best practice or standard to name it with an uppercase letter. So if we wanted to create our constructor representing our friends it might make sense to call it something like Friend and make that first letter a capital letter. So we're going to call this Friend. Add our parentheses which is where we'll be adding our parameters, and then open and close our curly brackets. So since we're creating a function that's going to be creating our objects we need to add our properties that it's going to be creating each time we call it inside. And rather than adding our properties as a comma separated list like we do in an object literal we have a special keyword that refers to the object we're creating and that's called this. So rather than saying name which only refers to the Lisa object since we're creating a template here the this keyword is going to refer to whatever we create using our function. So it's a more general way of using or creating properties and our object constructor. And this will make more sense in a couple minutes when we start creating instances with our constructor we'll revisit this kind of concept. So we're going to use the this keyword. We'll say this.name for object is going to be a name. And this is going to be a parameter so we need to add it inside of our parentheses and then we need our t-shirt color so we'd say this.tshirtcolor is going to be tshirtcolor and then we need to add this as a parameter as well so I'm going to add that comma and tshirtcolor. So now we have a function. It's going to expect a name and a t-shirt color as arguments and then it's going to create an object and set the properties to whatever values we pass through the functions. So if we wanted to create an object for our friend Denny we could say var denny. Use our assignment operator and instead of listing our his properties one by one like we did with our object literal we're going to use our constructor and we use a new keyword to create an instance of our constructor. So we can say Denny is a new and then we're going to use our constructor so he's a new friend and then we need to add our arguments in parentheses. And you can see it's already pulling up for us the arguments it expects to see. So you can see it expects a name and a t-shirt color as well. So his name would be Denny and we'd add a comma and his t-shirt color would be green and then we can add our semicolon. So just to kind of test this out and see if this is working we're going to use our alert command and say what object, so Denny is our object and go ahead and tell us his name using that dot notation. So if I hit Control S to save then we should see his name alerting in a popup box in our browser. So I'm going to hit Control S to save and you can see that it's returning the name we passed to Denny. So what this is doing here is when we're using our constructor we're basically just invoking a function or calling a function that is creating an instance of our friend template or our friend constructor. So it's going to take our argument so for example we pass through Denny and it's going to say Denny's the name so I'm going to create a property for Denny and I'm going to set this .name to be Denny. So in effect as it's going through our function here it's saying our object so set denny.name to be Denny and then it's going to set out object denny.name the t-shirt color, excuse me, to be green. But by creating our constructor we reduce all that repetition in our code. So if we wanted to very quickly and easily be able to create objects for all of our friends we could just say var Lisa is a new friend, so we could say Lisa and then her t-shirt color would be red and we get the same, whoops if I can type correctly, the same end result as we do with our object literal but we can reuse this as many times as we want and avoid any kind of repetition in our code. So now that we've taken a look at objects constructors and how we can reuse them to create prototypes or templates for an object in our next lesson we're going to continue to talk about objects and learn about object oriented programming.
What is Object Oriented Programming?
This and the Global Object
Local and Global Scope
Coding Conventions and Using Jslint
Revisiting Our Game
In this lesson we'll be revisiting our game from Volume Two, and seeing how it can change using objects in our code. Since the main theme of Volume Three has been learning how to use objects in our code, and the concept of object oriented programming, I want to take a look and see how our game might change using objects in our code. And rather than watch me write out the code line by line like we have in the last two volumes, since our code is starting to very much increase in complexity and length, I think it makes more sense to kind of take a look at our code and go through it line by line, rather than watching me type all of this out. So first let's go ahead and take a look at our game and how I changed it and then we can take a look at the code itself. So you can see we still have our beginning scenario, here, so we're alerting and kind of setting the stage. And then we're starting with a random scenario, so you can see we have a little beginning scenario here. So you press OK, and now it's going to ask us to name our character, so maybe we can name our character Bob. We can press OK, and then it's going to ask us to choose a class, which is pretty cool. You can see that the complexity of our game, here, is really starting to evolve and be more familiar in kind of a RPG type situation where you have the class, you have stats and you can choose different paths. So we have three different classes to choose from, we have soldier, doctor, or politician, and all of these are going to affect the outcome of our game, here, so let's say maybe we're going to be a politician, so I can say politician, press OK. And then it's going to alert our class, here, and our name, and our scenario, now, so it's much more personalized, here, as we're going through our story. Then we have our scenario, in which we encounter a zombie. So we have two actions we can take, now, we can attack or we can attempt to sneak by the zombie. So, depending on what class we chose, we might have different strengths that affect this outcome. So maybe I want to attack, and we can see the result here, we charged the zombie, we crushed our foe, press OK. Just kidding, (laughs) we're not strong 'cause we didn't choose the soldier class, so we're actually bitten by the zombie and we die, 'cause we failed our class check, which is happening here in our code. So rather than winning we spend eternity with the zombie, and that's the end of our game. And then we see the results, "you lose." So let's go ahead and take a look at the code and see how I got to this kind of result. So I'm going to go ahead and drag out the window, here, so we can see more of our code, and I'll go ahead and add comments in here and explain more in depth, and it'll be in our chapter, or lesson 10_end folder, so you'll be able to see the comments in that folder after we finish. But I've removed them for now so we can read through this easier without having to see all of those in there. So the first thing I've done is I've declared a variable which is going to store the outcome or whether we win or lose. And if we scroll to the end of our code, here, the very last thing here is it's going to check an outcome, it's going to see if the outcome is lose, or if the outcome is win, and then we see "you lose" or "you win" based on the outcome, which is determined elsewhere in our code, which we'll get to in just a couple minutes. So we've seen our scenarios here in our prior volumes, so this is nothing new here, we just have a list of very, of possible scenarios here. And it's going to alert a random scenario here to start with which we saw in our last lesson as well. We still have our random number function, so all of this is from last volume. If you want to remember how we wrote that, you can go back and watch that in Volume Two. So, the first new code here is starting here on line 26, where I created an object for the character. Since we're modeling real life things in our code, it makes perfect sense to have our character, and our character has certain properties that help describe our character as well. You'll notice I used an object literal instead of an object constructor, because we only have one main character, so it makes sense to use a literal, or, to instantiate our object at the same time we create it. So I've added a couple properties here to our character, we have health, we have strengths, and we also have stealth. And all of these are going to be used later down here in our code. Then we have a name, which is just a prompt, and it stores a response to this question as the name of our character. That way, anywhere else in our code where we want to refer to that name, we can just say character.name like you see down here. So the last thing inside of our character object is we just have a class which is storing the result to a response and it's asking us to choose from three different classes. We have the two lower case method here, that way we can type in any of these and it's going to convert it to all lower case so it works that way if someone types in "Soldier," like this, rather than "soldier" lower case, either one is going to work. Further down here, I also did a check, checks to see if someone typed in their name in our prompt, that way if someone tries to be funny, we can go ahead and see this, press OK, if we decide not to enter a name here, then after this check it's going to alert the user that they still need to enter their name. So if you choose not to enter a name, then it just gives you a random name. So moving on, so it's going to say if this doesn't exist, we can use this not operator, say, so if, no character name, if not character name, then go ahead and give another prompt asking them to enter their name again. Then once again, this is the second part we saw. If they still don't enter a name, then it's just going to assign them a random, kind of unfortunate name there. So after our name check here, just to see if no, the person, the player, doesn't enter a name, we have our three different classes. So we're saying if the character class is set to soldier, which is all based on the response to our prompt up here, so if soldier the character's going to get a bonus strength of five. If their character class is a politician their stealth, they're going to get a bonus to stealth of five, so we'll go from zero to five, or zero to five. Or, if they're a doctor, their health will go from five, they just get a little bonus to health, and their health is increased to seven. Then we have our first scenario, where you encounter the zombie, and you have the option to either attack or to sneak by the zombie, so it's taking this prompt and it's storing whatever you type in as a variable of choice. So now we're checking, we're saying if our choice, if whatever you entered here is equal to the String attack, then it's going to perform one more check and it's going to see if the strength is five. And if your strength is five, meaning if you're a soldier, then you're able to slay the zombie and loot the store. And then the outcome is win, and then it'll also outcome, it'll alert that you win. And then your character's strength increases as the result of this encounter. So since you have successfully beaten it, you've now gotten stronger, and your strength is increasing. Which, just a little note here, our increment operator, here, our ++s, when we use JSLint, it throws up a little error here. So we can see that we have two little ++s here, and we also have a little pesky space there, as well, so I can go ahead and delete that and fix that error. Woops. So it's going to throw up an error whenever we use that increment operator, because the author of JSLint, woops, we're getting another little Live Preview error since we're coming in here and messing around. But since the author doesn't care for this increment operator it's going to throw up an error, but it's a common convention so you can use the increment operator if you want. If you want to search that problem or research that problem, see why he doesn't like it, then you can just go ahead and search for this error in a search engine, and you can read all you ever cared to about the increment operator. So, moving on, it's going to check for our character strength, see if it's equal to five, otherwise if it's less than five, you're not going to be able to defeat the zombie using strength and your outcome is going to be to lose. Now, if you chose sneak instead of attack, so it's going to say if attack, run through all this, but if you chose sneak, or if you also chosen sneak by the zombie, that way there's a little flexibility in what the user's typing and you could say sneak, or sneaky by the zombie, then it's going to check your stealth, and if you successfully have stealth, so if you chose politician, you're going to be able to sneak by the zombie. Otherwise, if you chose doctor or warrior, soldier, then your stealth is going to be less than five and you're not going to be able to sneak by the zombie. But we have a little additional check, here, that says, if your stealth is less than five but your strength is five, so if you're a soldier, if you fail the stealth check you can still sneak by the zombie using your strength and crush him and then your outcome is equal to win. Otherwise, if you fail the stealth check and the strength check, then you just go ahead and lose. And then we have our final check of outcome equals lose, and outcome equals win. So you can see here just by using objects and properties of our object, how we've really made our game much more dynamic and much more interesting. And I know this is kind of a high-level overview of the code, here, but like I said, if you want to go here and play around I'll add comments here, and you can take a more in-depth look at this code. I've also gone ahead, here, if I shrink my window, and I've added our games from the previous volumes so you can compare them and see how our game has evolved throughout time. So we have volume1js and we have volume1.html, so if we double-click this and open that up in the browser, then we can see our game from Volume One. If you want to see the game from Volume Two, you can just go ahead and bring this up in the browser and do the same thing and compare the code, and see how we've changed and learned and evolved as we've gone throughout our volumes. So, now that we've taken a look at how our game could change by incorporating an object into our code, in our next lesson we're going to get our Volume Three assignment.
Volume 3 Assignment
Susan is a web design author for Pluralsight. Growing up, Susan was both a passionate artist as well as a computer tech aficionado. When she discovered the world of web development, she found that...
Released17 Jan 2015