JavaScript Classes and Constructors

Before classes were introduced, developers used constructor functions to create similar objects.

Old:

function Player(name) {
  this.name = name;
}

Player.prototype.greet = function() {
  console.log(`Hi, I'm ` + this.name);
};

Then ECMAScript 6 (ES6) was approved as a standard on June 17, 2015, by the Ecma International General Assembly.

ES6 is the latest major version of JavaScript, and introduced big features like classes.

New:

class Player {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hi, I'm`, this.name);
  }
}

Why Use Classes?

  • To organize your code better.
  • To create multiple objects of the same structure and behavior (like different players, cars, or users).
  • To bundle together data (properties) and functions (methods) into one reusable structure.
  • Makes it easier to define multiple objects that have the same properties

What Is a Constructor?

The constructor() is a special method inside a class that gets called automatically when a new object is created using new.

It’s where you set up the object’s initial values (like name, score, or age).

Example:

%%javascript

class Player {
    constructor(name, score) {
        this.name = name;
        this.score = score;
    }
    greet() {
        const message = `Hi! My name is ${this.name} and my score is ${this.score}!`;
        console.log(message);
    }
}

// Create a new Player object
const player1 = new Player('Alex', 42);
player1.greet(); // Output: Hi! My name is Alex and my score is 42!

How It Works:

  • class Player defines the blueprint.
  • constructor(name, score) runs automatically when you create a new Player.
  • this.name and this.score store data specific to that object.
  • The greet() method uses template literals to print info.

Creating Multiple Instances

You can make multiple objects (or instances) from the same class. This may be of use in game development when you want to have many different characters with similar properties.

%%javascript
const player1 = new Player('Jordan', 99);
const player2 = new Player('Taylor', 120);

player1.greet();
player2.greet();

In our Cookie Clicker game, we can use classes and constructors the same way game developers do to organize their code.

Think about the game: you start by clicking a big cookie to earn one cookie per click. But then, you can buy buildings (like bakeries or factories) that automatically produce cookies for you.

Each building has:

  • a name (like “Bakery” or “Factory”)

  • a cookies-per-second (CPS) value that shows how fast it produces cookies

  • a cost that tells you how many cookies you need to buy it

This is a perfect situation for a class — because every building follows the same structure, but has different values.

We can make a Building class that acts as a blueprint for all the types of buildings in the game.

When we use the constructor, we can pass in the building’s unique details (like its name, CPS, and cost). That way, we don’t need separate chunks of code for each building — we can just create new instances of the same class.

%%javascript
class Building {
    constructor(name, cps, cost) { // cps = cookies per second
        this.name = name;
        this.cps = cps;
        this.cost = cost;
    }
    info() { //this is a method that prints the cookies per second and costs
        console.log(this.name, `produces`, this.cps, `cookies per second and costs`, this.cost, `cookies.`);
    }
}

const bakery = new Building('Bakery', 1, 50);
const factory = new Building('Factory', 10, 500);

bakery.info();
factory.info();

Classes inside classes

Much like math, where you have composite functions such as f(g(x)), you can have classes inside of classes. However, each class can only have one constructor.

%%javascript
class Player {
    constructor(name, score) {
        this.name = name;
        this.score = score;
        this.stats = new Player.Stats(0, 0); // create a Stats object for each Player
    }

    greet() {
        console.log(`Hi! My name is`, this.name, `and my score is`, this.score + `!`);
    }

    // inner class
    static Stats = class {
        constructor(wins, losses) {
            this.wins = wins;
            this.losses = losses;
        }

        recordWin() {
            this.wins++;
        }

        recordLoss() {
            this.losses++;
        }

        showRecord() {
            console.log(`Wins:`, this.wins, `Losses:`, this.losses);
        }
    }
}

// Example usage
const player1 = new Player("Ishan", 120);
player1.greet();
player1.stats.recordWin();
player1.stats.showRecord();

<IPython.core.display.Javascript object>