AI Hints
JavaScript · Lesson 70 of 138

Classes

Blueprints for objects.

⏱ 2 min read▶ Video at 1:25:24🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

If you need many objects with the same shape and the same methods, like a hundred bank accounts, writing each object by hand is tiring. A class is a blueprint. You describe the shape once, then make as many objects from it as you like.

Classes
From the video: Classes
  • Many objects, same shape
  • Writing each by hand?
  • A class is a blueprint

class and new

The class keyword, then a name with a capital letter. The constructor runs when we make a new object, and sets up its properties with this. Methods go inside the class too. New creates an object from the blueprint. Each object, called an instance, has its own data. Run it.

app.jsjavascript
class Account {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  deposit(amount) {
    this.balance += amount;
  }
}

const a = new Account("Ana", 100);
const b = new Account("Ben");
a.deposit(50);
console.log(a.owner, a.balance, "|", b.owner, b.balance);
Output
Ana 150 | Ben 0

Classes and objects

The class is the blueprint, and each object made with new is an instance. All the instances share the same methods, but each has its own properties. Class names use a capital first letter, called Pascal case, so you can tell them apart from normal functions.

keyvalue
class Name { }the blueprint
constructorsets up properties
new Name()make an instance
PascalCaseclass names

Summary

A class is a blueprint for objects. The constructor sets up each instance, and new creates one. Next, more about methods and checking instances.

Key takeaways
  • class + constructor
  • new creates instances
  • Each has its own data
Next up: Class Methods — and instanceof