Hone

Lessons · JavaScript · classes and new

A class builds objects with new

A class describes what a kind of thing has and does. new Dog('Rex') builds one Dog and runs its constructor on it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A user, an order, a game piece, a connection: real programs are full of things that carry their own data and actions. A class keeps the two together instead of scattering them across plain objects and loose functions.

How to think about it

Ask: is this a KIND of thing I will make many of? Write a class for the kind; build each one with new. The class name is capitalised, the objects are ordinary variables.

Worked example

class Dog {
The blueprint.
  constructor(name) {
Runs once per new Dog.
    this.name = name;
this is the object being built.
  }
  bark() { return this.name + ' barks'; }
A method: a function every Dog has.
}
const rex = new Dog('Rex');
new builds the object and runs the constructor.
console.log(rex.bark(), typeof Dog);
Rex barks function

Your turn

Build one Cat from the class.

class Cat {
  constructor(name) { this.name = name; }
}
const tom =  Cat('Tom');

The trap

Leaving out new. Dog('Rex') throws 'Class constructor Dog cannot be invoked without new'; a class is not a plain function call.

Practise classes and new on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.