WEEK: 7
Active: February 24th - March 1st
Work Due: March 2nd @ 11:59 PM

Classes in JavaScript

Enough talking, let’s explore how to start writing our classes, so you can see why they are so powerful!

The class Keyword

The first thing we need is a new keyword! To write a class, we are going to use the keyword class.

The class name always follows this keyword.

An open curly brace follows the name, and the class ends with a closing curly brace. The curly braces contain properties/attributes and methods.

Class Naming Conventions

Before we can go further, let’s first talk about class naming conventions. For all except one rule, you should follow the same naming conventions that you do for variable names.

The one exception is that you should start class names with a capital letter.

In Practice

In practice, defining a class will have the following structure.

class MyFavoriteClass {
    // class methods/functions
}


Methods

When defining a class, functions are the things that do stuff in the class.

Methods is written within the function block - between the curly braces - of a class definition.

Writing methods within classes is practically identical to defining standalone functions.

Method Name

To write a method, you simply need to write its name, following function naming conventions (i.e. lower case letter to start the method name).

Input Parameters

Parentheses contain any input parameters for the specific method.

Function Block

Finally, you add a function block ({}). You will put all of the stuff for the method to do, within this function block.

Multiple Methods

To write multiple methods, separate each function with a new line. (This is more for the style than anything error specific). Then repeat the above steps.

Example Code

// a class definition
class MyFavoriteClass {

    // method 1
    sayHello( name1, name2 ) {
        // method function block
        // Do stuff here
        console.log(name1 + " says hello to " + name2);
    }

    // another method
    callMeCharlie() {
        // method function block
        console.log("Well call me Charlie");
    }
}

Not bad, right? Let’s take a look at the constructor.


Previous section:
Next section: