I like hip hop, so let’s say that we want to create an object that represents my favorite hip hop artist, the RZA from the Wu-Tang clan.
We could create an object literal that looks like this.
That’s pretty straightforward, right? Now, what if we want to make an object that represents each member of the Wu-Tang Clan?
Step 1: Class declaration
Next, we will need to add a constructor method, the constructor() method is a special method that gets called when an instance of the WuTangClanMember class is created. I like to think of the constructor as the burrito artists at Chipotle. They accept certain parameters such as tortilla, rice, beans, protein, veggies, etc . If you give them the following arguments flour tortilla, brown rice, pinto beans, sofritas, and stir-fry veggies, you will get a burrito with those things in it. Now, let’s take a look at how this works with our WuTangClanMember class.
Step 2: Add a constructor method
Now that we have our constructor set up, let’s look at how we can use methods with classes — after all, our objects would be boring if they didn’t do anything.
Step 3: Add methods
Now that we have our class of WuTangClanMember set up, we can use that to create instances of all of each Wu-Tang Clan member (This is also known as instantiating a WuTangClanMember). In order to create an instance of WuTangClanMember, we need to use the new keyword. Now, instead of creating an object literal for each Wu-Tang Clan member, we can instantiate instances of our “WuTangClanMember” class and save ourselves a lot of code.
Step 4: Instantiating instances of a class
Now, if you call the getWhatRulesEverythingAroundMe() method on each of our WuTangClanMembers, you can see that cash rules everything around each of them.