Classes
Programming Languages · JavaScript Objects · 15 min
Use classes as blueprints to build many objects with the same shape and methods.
A class is a blueprint
A class is a blueprint for making objects. Its constructor runs when you make a new object, and sets it up using this. Make an object from a class with new.
class Dog {
constructor(name) {
this.name = name;
}
}
const rex = new Dog("Rex");
console.log(rex.name); // Rex
Create a class
Catwhose constructor takesnameand stores it inthis.name.Make
const cat = new Cat("Luna")and printcat.name.
A constructor with several values
A constructor can take as many values as you need. Store each one on this.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Give
Booka constructor that takestitleandpagesand stores both.Make
const book = new Book("Dune", 412)and printDune has 412 pagesusingbook.titleandbook.pages.
Methods in a class
Methods go inside the class, after the constructor, with no function keyword. Every object made from the class gets them, and this is that object.
class Lamp {
constructor() {
this.on = false;
}
toggle() {
this.on = !this.on;
}
}
Add a method
increase()toCounterthat adds 1 tothis.count.Call
counter.increase()three times, then printcounter.count.
Many objects, one class
The real power of a class: write it once, make as many objects as you like. Each one has its own values but shares the same methods.
const a = new Pet("Rex", "woof");
const b = new Pet("Tom", "meow");
Make two pets:
"Rex"who says"woof"and"Tom"who says"meow".Call
speak()on both pets.
extends: building on another class
extends makes a new class that gets everything from an existing one, and then adds its own extras.
class Vehicle {
constructor(name) { this.name = name; }
}
class Bike extends Vehicle {
ring() { console.log("Ring ring!"); }
}
A Bike uses Vehicle's constructor, so new Bike("BMX") still sets name.
Create
class Bird extends Animalwith a methodfly()that prints the bird's name andflies away.Make
new Bird("Kiwi"), then call itsdescribe()andfly()methods.
Put it together: a bank account
Build a class from scratch: a constructor that sets things up, and methods that change the object. Then take it for a spin.
Create
class BankAccountwhose constructor takesowner, stores it, and setsthis.balanceto0.Add
deposit(amount)that adds to the balance andwithdraw(amount)that takes it away.Make an account for
"Zoe", deposit 50, deposit 20, withdraw 30, then printZoe has $40using itsownerandbalance.
More in JavaScript Objects
Previous: Objects · Next: Closures and Scope