WEEK: 11
Active: March 21st - April 3rd
Note: Spring Break runs from March 23rd - March 31st
Work Due: April 4th @ 9:00AM

Classes in JavaScript

Enough talking, let’s explore how to start writing our own 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.

This keyword is always followed by the class namespace.

The namespace is followed by a function block, which contains the methods defining the class.

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 ClassName {
    // class methods
}

Methods

When defining a class, methods are the “how-to” of the class. You can think of methods as a class specific function.

Methods are written within the function block 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. a lower case letter to start the method name).

Input Parameters

This is then followed by a set of parentheses containing 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, simply separate each method with a new line. (This is more for style than anything error specific). Then repeat the above steps.

Example Code

// a class definition
class ClassName {

    // method 1
    method1( inputParameter1, inputParameter2 ) {
        // method function block
        // Do stuff here
        console.log(inputParemeter1);
    }

    // another method
    anotherMethod() {
        // method function block
        // Do stuff here
    }
}

Previous section:
Next section: