A Blueprint for Objects
JavaScript Classes
Classes give you a clean syntax for creating many similar objects. A constructor runs on each new instance; methods are shared.
What you'll learn
- Define a class with a constructor and methods
- Create instances with `new`
- Understand that methods are shared via the prototype
A class is a blueprint for creating objects of a certain shape.
The constructor runs each time you create an instance; methods on
the class are shared across all instances.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const ada = new User("Ada", 36);
const lin = new User("Lin", 28);
console.log(ada.greet()); // "Hi, I'm Ada"
console.log(lin.greet()); // "Hi, I'm Lin" Key things:
class User { … }declares a class.constructorruns when younewan instance.thisinside the constructor and methods is the instance.new User(…)creates a new instance, calling the constructor.
Methods Are Shared
All instances share the same method functions — they’re stored on the class’s prototype (covered in the previous lesson).
class User {
constructor(name) { this.name = name; }
greet() { return `Hi, ${this.name}`; }
}
const a = new User("Ada");
const b = new User("Lin");
console.log(a.greet === b.greet); // true — same function reference This saves memory and means an update to a method affects all existing instances.
Instance Properties
The simplest form sets properties inside the constructor with this.x = ….
You can also declare instance properties at the top of the class (ES2022) — they’re set on every new instance before the constructor runs:
class Counter {
count = 0; // default for every new Counter
increment() {
this.count++;
}
}
const c = new Counter();
c.increment();
c.increment();
console.log(c.count); // 2 class vs Plain Object
If you only need one of something, a plain object is enough:
const config = {
apiUrl: "https://example.com",
timeout: 5000,
}; If you’ll make many similar instances with their own state, a class is the natural fit.
Forgetting new
Calling a class without new throws.
class User {
constructor(name) { this.name = name; }
}
// User("Ada"); // TypeError: Class constructor User cannot be invoked without 'new'
const ada = new User("Ada"); // ✅
console.log(ada); Methods Use Regular Function Syntax
Class methods are regular methods, not arrows. this inside a method
follows the normal “method call” rule.
Try It Yourself
Exercise
A BankAccount class
// declare BankAccount here
const acct = new BankAccount(100);
acct.deposit(50);
acct.withdraw(30);
console.log(acct.getBalance());
💡 Show hint
✅ Show solution
class BankAccount {
constructor(initial) {
this.balance = initial;
}
deposit(amount) { this.balance += amount; }
withdraw(amount) { this.balance -= amount; }
getBalance() { return this.balance; }
}
const acct = new BankAccount(100);
acct.deposit(50);
acct.withdraw(30);
console.log(acct.getBalance());
Up Next
Build one class on top of another with extends.