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.
class User {
constructor(first, last, e) {
this.f = first;
this.l = last;
this.email = e;
}
}
var userOne = new User("Paul", "O'Connor", "poconnor@elevenfifty.org");
console.log(userOne.first); //undefined
console.log(userOne.f); //Paul
console.log(userOne.l); //O'Connor
console.log(userOne); //User {f: "Paul", l: "O'Connor", email: "poconnor@elevenfifty.org"}
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:
//We name the class
class User {
//We call the constructor function and create parameters.
//These will be values that we want to be passed in and stored in the object.
constructor(first, last, e) {
//On the right side of these expressions, the word 'first', 'last', and 'e' below,
//we have the value that is getting passed into the parens when the object is created.
// vvv
this.f = first;
this.l = last;
this.email = e;
//^^^^^^^^
//On the right side we have the actual properties of the object.
//The left side stores the incoming value from the right side as
//the property for 'this' specific object being created.
}
}
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