Introduction and Lesson Overview

Welcome to your next JavaScript session! We'll be discussing Classes, which are essential blueprints for creating objects. We'll cover class syntax, constructors, methods, and class inheritance. Are you ready to explore JavaScript Classes? Let's unravel the magic!

Understanding the Concept of Classes

In JavaScript, Classes serve as blueprints for creating objects. Imagine building houses; each house shares a similar structure — doors, windows, a roof, rooms — but the details may vary, such as the number of rooms or doors. Similarly, each object of a class will have a consistent structure, but the details may differ.

class House {
    // Stay tuned for properties and methods.
}

Here, House is a Class. An object of this Class would be an individual house.

Exploring the Class Constructor

When creating an object from a class, the new keyword calls the constructor inside that class, initiating a new object called an instance of the class.

class Car {
    constructor(brand) {
        console.log("The Car constructor has been called");
        this.carname = brand;
    }
}
let myCar = new Car("Toyota"); // prints "The Car constructor has been called"

We've created a myCar object of the Car Class with carname set as 'Toyota'. The myCar object is an instance of the Car Class.

In JavaScript classes, this refers to the instance of the class. In other words, when an object is created using a class, this stands for that particular object.

When this is used inside a class's constructor method, it refers to the newly created instance of that class. In our code, this.carname = brand; means the carname property of the newly created object is set to the value of brand passed to the constructor.

You can access the property carname of the instance myCar as follows:

console.log(myCar.carname);  // Outputs: 'Toyota'
Introduction to Class Methods

Class Methods allow an object of the class to interact with its properties. Consider a simple Player class for a game, for example. A player has properties like name and score and methods like increaseScore.

class Player {
    constructor(name, score) {
        this.name = name;
        this.score = score;
    }

    increaseScore() {
        this.score++; // Increase Player's score by 1, the same as this.score += 1;
    }
}

let player1 = new Player('John', 0);
player1.increaseScore();

console.log(player1.name); // Output: John
console.log(player1.score); // Output: 1

Note that when defining class methods, we omit the function keyword.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal