Execute Program

Modern JavaScript: Classes

Welcome to the Classes lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • JavaScript gained a new class syntax in 2015. This new syntax should look familiar to programmers who already know other common object-oriented languages like Java, C#, Python, or Ruby.

  • If you already know an object-oriented language, this first lesson on classes might be very easy. But we'll soon turn to issues that are specific to JavaScript's version of classes.

  • Classes describe the shape of an object: what properties and methods (functions) it has. Class method definitions look like the shorthand method syntax that we already saw in literal objects: methodName() { ... }.

  • We construct an instance of a class with new: new MyClass(). The instance is an object with all of the properties and methods specified by the class.

  • >
    class MsFluff {
    name() {
    return 'Ms. Fluff';
    }
    }
    new MsFluff().name();
    Result:
    'Ms. Fluff'Pass Icon
  • Classes can have constructors, which are special methods that prepare instances of the class for use.

  • >
    class MsFluff {
    constructor() {
    this.name = 'Ms. Fluff';
    }
    }
    new MsFluff().name;
    Result:
    'Ms. Fluff'Pass Icon
  • When we write new MsFluff(), we're "instantiating" the class, giving us an "instance".

  • In most cases, we'll want more generic classes, like a Cat class that works for any cat. The Cat class takes name as an argument, then stores the name.

  • In the next example, we instantiate two Cat objects inside an array, then immediately access their names.

  • >
    class Cat {
    constructor(name) {
    this.name = name;
    }
    }
    [new Cat('Ms. Fluff').name, new Cat('Keanu').name];
    Result:
    ['Ms. Fluff', 'Keanu']Pass Icon
  • Here's a code problem:

    Define a Cat class whose constructor takes both a name and an age. Store the name and age as properties on this.

    class Cat {
    constructor(name, age) {
    this.name = name;
    this.age = age;
    }
    }
    [
    new Cat('Ms. Fluff', 4),
    new Cat('Keanu', 2),
    ];
    Goal:
    [{name: 'Ms. Fluff', age: 4}, {name: 'Keanu', age: 2}]
    Yours:
    [{name: 'Ms. Fluff', age: 4}, {name: 'Keanu', age: 2}]Pass Icon
  • Here's a code problem:

    Use new to instantiate an array of two cats: 'Ms. Fluff' and 'Keanu'.

    class Cat {
    constructor(name) {
    this.name = name;
    }
    }
    const cats = [new Cat('Ms. Fluff'), new Cat('Keanu')];
    cats.map(cat => cat.name);
    Goal:
    ['Ms. Fluff', 'Keanu']
    Yours:
    ['Ms. Fluff', 'Keanu']Pass Icon
  • Classes can contain methods, which are functions that any individual instance of the class can call. These methods can access the object's properties with this.somePropertyName.

  • >
    class Cat {
    constructor(name, vaccinated) {
    this.name = name;
    this.vaccinated = vaccinated;
    }

    needsVaccination() {
    return !this.vaccinated;
    }
    }
    [
    new Cat('Ms. Fluff', true).needsVaccination(),
    new Cat('Keanu', false).needsVaccination(),
    ];
    Result:
    [false, true]Pass Icon
  • Here's a code problem:

    Define an area method on the Rectangle class.

    class Rectangle {
    constructor(width, height) {
    this.width = width;
    this.height = height;
    }

    area() {
    return this.width * this.height;
    }
    }
    [new Rectangle(3, 4).area(), new Rectangle(5, 6).area()];
    Goal:
    [12, 30]
    Yours:
    [12, 30]Pass Icon
  • We can't call instance methods directly on the class itself; we can only call them on instances. If we try to call instance methods on the class, that's an error. (You can type error when a code example will throw an error.)

  • >
    class Cat {
    constructor(name, vaccinated) {
    this.name = name;
    this.vaccinated = vaccinated;
    }

    needsVaccination() {
    return !this.vaccinated;
    }
    }
    Cat.needsVaccination();
    Result:
    TypeError: Cat.needsVaccination is not a functionPass Icon
  • The new keyword is required when instantiating classes: new Cat(...). If we try to create a Cat by calling the class like a function, we'll get an error.

  • >
    class Cat { }
    Cat();
    Result:
    TypeError: Class constructor Cat cannot be invoked without 'new'Pass Icon
  • The class system covered here is relatively new to JavaScript. There's also an older, prototype-based system, which is unusual and therefore unfamiliar to many programmers. Many recent changes to the JavaScript language, including those covered in this course, were specifically added to save us from worrying about prototypes at all.

  • We recommend avoiding prototypes as much as possible. As one data point, Execute Program itself is written entirely in TypeScript, a superset of the JavaScript language. We use classes when they're convenient, and never use prototypes.