Your game needs 50 animals. Each animal has a name and a sound, and it can speak. Writing 50 objects one by one, each with its methods, is far too much work. What you need is a mould: you write the shape once, then make as many objects as you like.
In JavaScript, a mould for objects is called a class. Inside a class you write two things: what data each object holds, and which methods it can run. Then you make the objects with new. A class still works through the prototypes from the previous lesson. Only the way you write it is shorter.
A mould with class
This example creates the class Animal, then makes two animals from it:
class Animal {
constructor(name, sound) {
this.name = name
this.sound = sound
}
speak() {
return `${this.name}: ${this.sound}!`
}
}
const a = new Animal('Cow', 'Moo')
const b = new Animal('Duck', 'Quack')
console.log(a.speak()) // Cow: Moo!
console.log(b.speak()) // Duck: Quack!
class Animal { ... }defines the mould. Class names usually start with a capital letter.constructor(name, sound)is a special method that runs automatically every timenew Animal(...)is called. Its job is to store data on the new object throughthis, for examplethis.name = name.speak() { ... }is a method. You write a method directly inside the class, without thefunctionkeyword. Inside a method,thisis the object that called it:a.speak()readsa's data, andb.speak()readsb's data.new Animal('Cow', 'Moo')makes one new object. An object made withnewis called an instance. A class can't be called withoutnew:Animal('Cow', 'Moo')causes aTypeError.
If you change a.name, b.name stays the same. Each instance has its own data. Only the methods are shared. They are stored on Animal.prototype.
Using a class inside a function
This example uses the class Rectangle inside the function getPerimeter:
class Rectangle {
constructor(length, width) {
this.length = length
this.width = width
}
perimeter() {
return 2 * (this.length + this.width)
}
}
function getPerimeter(length, width) {
const box = new Rectangle(length, width)
return box.perimeter()
}
getPerimeter(4, 2) // 12
- The
getPerimeterfunction makes an instance withnew, calls its method, then returns the result withreturn. So there are tworeturns: one in the method, one in the function. If you forget either one,getPerimeterreturnsundefined. - The method reads data through
this.length, not justlength. Theconstructor's parameters only exist inside theconstructor. So store their values onthisfirst, so that other methods can read them.
Inheriting with extends and super
This example builds the class Cat from the class Animal above:
class Cat extends Animal {
constructor(name, color) {
super(name, 'Meow')
this.color = color
}
}
const milo = new Cat('Milo', 'orange')
milo.speak() // 'Milo: Meow!'
milo instanceof Cat // true
milo instanceof Animal // true
extends AnimalmakesCatinherit fromAnimal:Catgets everythingAnimalhas, includingspeak(). A class that inherits, likeCat, is called a subclass.Animalis its parent.super(name, 'Meow')runsAnimal'sconstructor, which stores the name and the sound. In a subclass,thisonly exists aftersuper()has run. So callsuper()on the first line of theconstructor. Writingthis.colorbeforesuper()causes aReferenceError.instanceofchecks whether an object was made from a class, by following its prototype chain.milowas made fromCat. BecauseCat extends Animal,milocounts as anAnimaltoo.
static methods
This example has a method that you call without making an instance:
class Temperature {
static toFahrenheit(celsius) {
return celsius * 9 / 5 + 32
}
}
Temperature.toFahrenheit(100) // 212
static makes a method belong to the class itself, not to each instance. You call the method through the class's name, Temperature.toFahrenheit(100), not through an object made with new. A static method suits a helper function that doesn't need any instance's data.
⚠️ What makes a class fail
- Commas between methods. In an object literal (an object written directly with curly braces), commas separate the methods. In a class they don't:
speak() {}, run() {}inside a class is aSyntaxError. - A method taken away from its object. After
const f = a.speak,f()is called with no object left of the dot. Code inside a class always runs in strict mode, sothisisundefined, andthis.namecauses an error. Calla.speak()directly, or bindthisfirst:a.speak.bind(a). - A method with no
return. A method that only calculates something, withoutreturn, returnsundefinedto the code that called it.
TL;DR: A class is a mould for making objects. An object made with new is called an instance. The constructor runs automatically when new is called and stores data on the instance through this. Methods are written without the function keyword and read data through this. Each instance has its own data, and the methods are shared. extends makes one class inherit from another. In the constructor of the class that inherits (the subclass), call super() first: it runs the parent class's constructor. instanceof checks whether an object was made from a class, or from a subclass of it. A static method is called through the class's name, not through an instance.
⚡ A mould with class
Write:
class Animal {
constructor(name, sound) {
this.name = name
this.sound = sound
}
speak() {
return `${this.name}: ${this.sound}!`
}
}
const a = new Animal('Cow', 'Moo')
a.speak() // Cow: Moo!
Meaning: The class Animal is a mould for making objects. The constructor runs automatically every time new is called and stores data on the new object through this. A method like speak() is written without the function keyword. An object made with new is called an instance. Each instance has its own data, and the methods are shared. A class can't be called without new.
⚡ Inheriting with extends and super
Write:
class Cat extends Animal {
constructor(name, color) {
super(name, 'Meow')
this.color = color
}
}
new Cat('Milo', 'orange').speak() // 'Milo: Meow!'
Guess first: what happens if this.color = color comes before super()?
A ReferenceError. In a class that inherits (a subclass), this only exists after super() has run the constructor of its parent, Animal.
Meaning: extends Animal makes Cat inherit everything Animal has, including the method speak(). super(name, 'Meow') runs Animal's constructor, which stores the name and the sound. Because this only exists after that, call super() on the first line of the constructor of the class that inherits.
⚡ static methods
Write:
class Temperature {
static toFahrenheit(celsius) {
return celsius * 9 / 5 + 32
}
}
Temperature.toFahrenheit(100) // 212
Meaning: A static method belongs to the class itself. So you call it through the class's name, Temperature.toFahrenheit(100), not through an object made with new. It suits a helper function that doesn't need any instance's data.