DEV Community

Wendy
Wendy

Posted on

Scouting Javascript Classes

Scouting Javascript Classes

Inspired by a conversation I heard yesterday I wanted to give a clear explaination of object-oriented JavaScript and classes. The first "space-time" key to understand classes is to understand object literals. You may be aware that code can be used to describe both abstract and real world objects. Object literals are a way of encapsulating data in a neat single package through key-value pairs of properties and methods. Since enhanced object literals have come into play with ES2015, it is even easier to create them.

Object Literal

Luna and Artemis

So, this is going to sound crazy, but the overheard conversation was between two cats talking about a magical heroine. Let's see if I can describe her as an object literal.

const sailorMoon = {
  humanName: 'Usagi',
  nickName: 'Meatball Head',
  birthday: 'June 30',
  age: 14,
  favoriteAnimal: 'Rabbit',
  favoriteColor: 'White',
  favoriteFood: 'Ice Cream',
  strength: 'Loyalty',
  weakness: 'Thunder',
  phrase: function() {
    console.log('Moon Prism Power Makeup!')
  }
}

Notice that our heroine's object literal is arranged within curly brackets and key-value pairs are separated with a comma. All of the key-value pairs are properties of const sailorMoon. The last pairing is called a method.
We can access different properties or methods of Sailor Moon using dot notation like so:objectName.propertyKey.

console.log(sailorMoon.nickName);
    'Meatball Head'

Sailor Scouts

Class Constructor

Our Sailor Moon object literal is all well and good, but imagine my astonishment on learning there were four other magical Sailor Scouts! There must be a quicker way to build our Sailor Senshi team than writing out the same object literal keys every time a new one magically makeups! Thanks to ES2015, yes there is! Classes in JavaScript are lovely syntatical sugar waving a moon crescent wand over object creation and inheritance issues.

With class, we can make a Sailor Scout blueprint and churn out four, five, even nine scouts with a few lines of code. Moon Cosmic Dream Action!

Outer Sailor Scouts

Let's start with declaring our class. Notice the name of the class is capitalized. This is common convention. Inside of our class, we will add a constructor method. The constructor is like a factory that will make all of the property values we request. We request these parameters by placing them in the (). So, what do you think a sailor scout needs?

class SailorScout {
  constructor(scoutName, humanName, birthday, element, favoriteColor, strength, weakness) {
  }
}

So we have our constructor and request list (parameters). Let's place some object properties in the constructor and link them to our parameters.

We need to use dot notation and the keyword this. In this case this refers to the object being created. It is linked to a property using dot notatation and set equal to a parameter.

class SailorScout {
  constructor(scoutName, humanName, birthday, element, favoriteColor, strength, weakness) {
    this.scoutName = scoutName;
    this.humanName = humanName;
    this.birthday =  birthday;
    this.element = element;
    this.favoriteColor = favoriteColor;
    this.strength = strength;
    this.weakness = weakness;
  }
}

Now we are ready to instantiate our Sailor Scout! Instantiate means to create. First we will declare a variable to hold the object. We set the variable equal to the keyword new and the class name, then we pass in our Sailor Scout's values as parameters.

const sailorMercury = new SailorScout('Sailor Mercury', 'Ami', 'September 10', 'Water', 'Blue', 'Intelligence', 
'Shyness')

Now if we console.log(sailorMercury) we should see all of Sailor Mercury's properties and values!

SailorScout {scoutName: "Sailor Mercury", humanName: "Ami", birthday: "September 10", element: "Water", favoriteColor: "Blue", strength: "Intelligence", weakness: "shyness"}

Adding Methods to Our Class

Sailor Scouts need to do something magical so we will need to add some methods to our Sailor Scout class. This is a similar process to adding a method to our Sailor Moon object literal. First, we want to add one more property to our Sailor Scout: magicalPhrase. Then we will use that property in a method we will name cast.

class SailorScout {
  constructor(scoutName, humanName, birthday, element, favoriteColor, strength, weakness, magicalPhrase) {
    this.scoutName = scoutName;
    this.humanName = humanName;
    this.birthday =  birthday;
    this.element = element;
    this.favoriteColor = favoriteColor;
    this.strength = strength;
    this.weakness = weakness;
    this.magicalPhrase = magicalPhrase;
  }

  cast() {
    console.log(this.magicalPhrase);
  }

}

Let's see this in action:

  const sailorMars = new SailorScout( "Sailor Mars", "Rei",  "April 17th", "Fire", "Red", "Psychic Abilities","Stubborness", "Mars Fire Ignite!")

  const sailorJupiter = new SailorScout("Sailor Jupiter", "Makoto", "December 5", "Thunder", "Green", "Physical Strength", "Impulsivity","Jupiter Thunder Crash!")

  sailorMars.cast();
  sailorJupiter.cast();

  Mars Fire Ignite!
  Jupiter Thunder Crash!

Mars Fire Ignite!

Congrats! You can now quickly create your own army of Sailor Senshi!!
Next time we will upgrade our Sailor Scouts with 'getters' and 'setters'!

Top comments (2)

Collapse
 
joeberetta profile image
Joe Beretta

Hi Wendy! Good job. Thank you for explaining classes in js. It's cool. And now I've questioned: what if add Init/Set methods for creating object with default options and editing it later.
And would be thankful if you would explain about es6/class more))) Thank you 🙏🙏🙏

Collapse
 
pachicodes profile image
Pachi 🥑

Great explanation Wendy, thank you soo much!