2.2: constructors
The constructor method is a special method that helps create and initialize an object created from a class. It works in tandem with the new
keyword.
Make sure to run the app at this point and check your values in the console. So here's a breakdown of the constructor, line by line:
So, think about why console.log(userOne.first);
comes back as undefined
. In JavaScript, undefined means a variable has been declared but has not yet been assigned a value. When we log userOne.first
, it's undefined because that property doesn't exist. While it is the parameter name in the constructor, it's not a property on the object. We could write console.log(userOne.spaghetti)
and get the same result.
We would actually get the same thing if we tried this console.log(userOne.stuff);
. Essentially in this case, we're trying to create a property called 'stuff' that doesn't exist as a property on our object. Currently, our properties are on that left side with f
, l
, & email
. By the way, usually we wouldn't write our properties with this clunky naming. This is simply a way to show you how this all works. We recommend that you reread all of this. You won't get it on the first pass.
Practice
You don't really understand this concept until you go write classes of your own. Try writing a Player class with three properties of name, number, and average points. Or try writing a Car class with make, model, and year. Whatever you do, make sure you have a firm grip on constructors before you go on. You can do all this in the same file.
Last updated